diff --git a/sdk/openai/openai/CHANGELOG.md b/sdk/openai/openai/CHANGELOG.md index 002ffa7d2f9a..a737d2e2d1f4 100644 --- a/sdk/openai/openai/CHANGELOG.md +++ b/sdk/openai/openai/CHANGELOG.md @@ -6,8 +6,13 @@ ### Breaking Changes +- `OnYourDataAuthenticationOptions`, `OnYourDataVectorizationSource`, `OnYourDataVectorizationSourceType`, `ChatCompletionsNamedToolSelection`, `ChatCompletionsToolDefinition`, `ChatCompletionsToolCall`, `ChatMessageContentItem`, `ChatRequestMessage`, `ChatFinishDetails` are renamed with `Union` postfix. +- `AzureCognitiveSearchQueryType`, `ChatMessageImageDetailLevel`, `ElasticsearchQueryType`, `FunctionCallPreset`, `ImageGenerationQuality`, `ImageGenerationResponseFormat`, `ImageSize`, `ImageGenerationStyle`, `OnYourDataAuthenticationType`, `OnYourDataVectorizationSourceType` union types no longer have fixed values. + ### Bugs Fixed +- Fix a bug where `ChatCompletionsFunctionToolCall` did not expose the `index` property for the streaming mode. + ### Other Changes ## 1.0.0-beta.11 (2024-01-25) diff --git a/sdk/openai/openai/generated/OpenAIClient.ts b/sdk/openai/openai/generated/OpenAIClient.ts new file mode 100644 index 000000000000..17f76abfbc07 --- /dev/null +++ b/sdk/openai/openai/generated/OpenAIClient.ts @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { TokenCredential, KeyCredential } from "@azure/core-auth"; +import { Pipeline } from "@azure/core-rest-pipeline"; +import { + AudioTranscriptionOptions, + AudioTranscription, + AudioTranslationOptions, + AudioTranslation, + CompletionsOptions, + Completions, + ChatCompletionsOptions, + ChatCompletions, + ImageGenerationOptions, + ImageGenerations, + EmbeddingsOptions, + Embeddings, +} from "./models/models.js"; +import { + GetAudioTranscriptionAsPlainTextOptions, + GetAudioTranscriptionAsResponseObjectOptions, + GetAudioTranslationAsPlainTextOptions, + GetAudioTranslationAsResponseObjectOptions, + GetCompletionsOptions, + GetChatCompletionsOptions, + GetChatCompletionsWithAzureExtensionsOptions, + GetImageGenerationsOptions, + GetEmbeddingsOptions, +} from "./models/options.js"; +import { + createOpenAI, + OpenAIClientOptions, + OpenAIContext, + getAudioTranscriptionAsPlainText, + getAudioTranscriptionAsResponseObject, + getAudioTranslationAsPlainText, + getAudioTranslationAsResponseObject, + getCompletions, + getChatCompletions, + getChatCompletionsWithAzureExtensions, + getImageGenerations, + getEmbeddings, +} from "./api/index.js"; + +export { OpenAIClientOptions } from "./api/OpenAIContext.js"; + +export class OpenAIClient { + private _client: OpenAIContext; + /** The pipeline used by this client to make requests */ + public readonly pipeline: Pipeline; + + constructor( + endpoint: string, + credential: KeyCredential | TokenCredential, + options: OpenAIClientOptions = {}, + ) { + this._client = createOpenAI(endpoint, credential, options); + this.pipeline = this._client.pipeline; + } + + /** + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. + */ + getAudioTranscriptionAsPlainText( + deploymentId: string, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsPlainTextOptions = { requestOptions: {} }, + ): Promise { + return getAudioTranscriptionAsPlainText(this._client, deploymentId, body, options); + } + + /** + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. + */ + getAudioTranscriptionAsResponseObject( + deploymentId: string, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsResponseObjectOptions = { + requestOptions: {}, + }, + ): Promise { + return getAudioTranscriptionAsResponseObject(this._client, deploymentId, body, options); + } + + /** Gets English language transcribed text and associated metadata from provided spoken audio data. */ + getAudioTranslationAsPlainText( + deploymentId: string, + body: AudioTranslationOptions, + options: GetAudioTranslationAsPlainTextOptions = { requestOptions: {} }, + ): Promise { + return getAudioTranslationAsPlainText(this._client, deploymentId, body, options); + } + + /** Gets English language transcribed text and associated metadata from provided spoken audio data. */ + getAudioTranslationAsResponseObject( + deploymentId: string, + body: AudioTranslationOptions, + options: GetAudioTranslationAsResponseObjectOptions = { + requestOptions: {}, + }, + ): Promise { + return getAudioTranslationAsResponseObject(this._client, deploymentId, body, options); + } + + /** + * Gets completions for the provided input prompts. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ + getCompletions( + deploymentId: string, + body: CompletionsOptions, + options: GetCompletionsOptions = { requestOptions: {} }, + ): Promise { + return getCompletions(this._client, deploymentId, body, options); + } + + /** + * Gets chat completions for the provided chat messages. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ + getChatCompletions( + deploymentId: string, + body: ChatCompletionsOptions, + options: GetChatCompletionsOptions = { requestOptions: {} }, + ): Promise { + return getChatCompletions(this._client, deploymentId, body, options); + } + + /** + * Gets chat completions for the provided chat messages. + * This is an Azure-specific version of chat completions that supports integration with configured data sources and + * other augmentations to the base chat completions capabilities. + */ + getChatCompletionsWithAzureExtensions( + deploymentId: string, + body: ChatCompletionsOptions, + options: GetChatCompletionsWithAzureExtensionsOptions = { + requestOptions: {}, + }, + ): Promise { + return getChatCompletionsWithAzureExtensions(this._client, deploymentId, body, options); + } + + /** Creates an image given a prompt. */ + getImageGenerations( + deploymentId: string, + body: ImageGenerationOptions, + options: GetImageGenerationsOptions = { requestOptions: {} }, + ): Promise { + return getImageGenerations(this._client, deploymentId, body, options); + } + + /** Return the embeddings for a given prompt. */ + getEmbeddings( + deploymentId: string, + body: EmbeddingsOptions, + options: GetEmbeddingsOptions = { requestOptions: {} }, + ): Promise { + return getEmbeddings(this._client, deploymentId, body, options); + } +} diff --git a/sdk/openai/openai/sources/generated/src/api/OpenAIContext.ts b/sdk/openai/openai/generated/api/OpenAIContext.ts similarity index 94% rename from sdk/openai/openai/sources/generated/src/api/OpenAIContext.ts rename to sdk/openai/openai/generated/api/OpenAIContext.ts index f92f7dd22710..0c1c89790ba9 100644 --- a/sdk/openai/openai/sources/generated/src/api/OpenAIContext.ts +++ b/sdk/openai/openai/generated/api/OpenAIContext.ts @@ -13,7 +13,7 @@ export { OpenAIContext } from "../rest/index.js"; export function createOpenAI( endpoint: string, credential: KeyCredential | TokenCredential, - options: OpenAIClientOptions = {} + options: OpenAIClientOptions = {}, ): OpenAIContext { const clientContext = getClient(endpoint, credential, options); return clientContext; diff --git a/sdk/openai/openai/generated/api/index.ts b/sdk/openai/openai/generated/api/index.ts new file mode 100644 index 000000000000..0a9a9a9c66d0 --- /dev/null +++ b/sdk/openai/openai/generated/api/index.ts @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +export { createOpenAI, OpenAIClientOptions, OpenAIContext } from "./OpenAIContext.js"; +export { + getAudioTranscriptionAsPlainText, + getAudioTranscriptionAsResponseObject, + getAudioTranslationAsPlainText, + getAudioTranslationAsResponseObject, + getCompletions, + getChatCompletions, + getChatCompletionsWithAzureExtensions, + getImageGenerations, + getEmbeddings, +} from "./operations.js"; diff --git a/sdk/openai/openai/generated/api/operations.ts b/sdk/openai/openai/generated/api/operations.ts new file mode 100644 index 000000000000..d821d24e6cae --- /dev/null +++ b/sdk/openai/openai/generated/api/operations.ts @@ -0,0 +1,1173 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + AudioTranscriptionOptions, + AudioTranscription, + AudioTranslationOptions, + AudioTranslation, + CompletionsOptions, + Completions, + ChatCompletionsOptions, + ChatCompletions, + ImageGenerationOptions, + ImageGenerations, + EmbeddingsOptions, + Embeddings, +} from "../models/models.js"; +import { serializeChatRequestMessageUnion } from "../utils/serializeUtil.js"; +import { + GetAudioTranscriptionAsPlainText200Response, + GetAudioTranscriptionAsPlainTextDefaultResponse, + GetAudioTranscriptionAsResponseObject200Response, + GetAudioTranscriptionAsResponseObjectDefaultResponse, + GetAudioTranslationAsPlainText200Response, + GetAudioTranslationAsPlainTextDefaultResponse, + GetAudioTranslationAsResponseObject200Response, + GetAudioTranslationAsResponseObjectDefaultResponse, + GetChatCompletions200Response, + GetChatCompletionsDefaultResponse, + GetChatCompletionsWithAzureExtensions200Response, + GetChatCompletionsWithAzureExtensionsDefaultResponse, + GetCompletions200Response, + GetCompletionsDefaultResponse, + GetEmbeddings200Response, + GetEmbeddingsDefaultResponse, + GetImageGenerations200Response, + GetImageGenerationsDefaultResponse, + isUnexpected, + OpenAIContext as Client, +} from "../rest/index.js"; +import { + StreamableMethod, + operationOptionsToRequestParameters, + createRestError, +} from "@azure-rest/core-client"; +import { uint8ArrayToString } from "@azure/core-util"; +import { + GetAudioTranscriptionAsPlainTextOptions, + GetAudioTranscriptionAsResponseObjectOptions, + GetAudioTranslationAsPlainTextOptions, + GetAudioTranslationAsResponseObjectOptions, + GetCompletionsOptions, + GetChatCompletionsOptions, + GetChatCompletionsWithAzureExtensionsOptions, + GetImageGenerationsOptions, + GetEmbeddingsOptions, +} from "../models/options.js"; + +export function _getAudioTranscriptionAsPlainTextSend( + context: Client, + deploymentId: string, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsPlainTextOptions = { requestOptions: {} }, +): StreamableMethod< + GetAudioTranscriptionAsPlainText200Response | GetAudioTranscriptionAsPlainTextDefaultResponse +> { + return context.path("/deployments/{deploymentId}/audio/transcriptions", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { + file: uint8ArrayToString(body["file"], "base64"), + filename: body["filename"], + response_format: body["responseFormat"], + language: body["language"], + prompt: body["prompt"], + temperature: body["temperature"], + model: body["model"], + }, + }) as StreamableMethod< + GetAudioTranscriptionAsPlainText200Response | GetAudioTranscriptionAsPlainTextDefaultResponse + >; +} + +export async function _getAudioTranscriptionAsPlainTextDeserialize( + result: + | GetAudioTranscriptionAsPlainText200Response + | GetAudioTranscriptionAsPlainTextDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return result.body; +} + +/** + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. + */ +export async function getAudioTranscriptionAsPlainText( + context: Client, + deploymentId: string, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsPlainTextOptions = { requestOptions: {} }, +): Promise { + const result = await _getAudioTranscriptionAsPlainTextSend(context, deploymentId, body, options); + return _getAudioTranscriptionAsPlainTextDeserialize(result); +} + +export function _getAudioTranscriptionAsResponseObjectSend( + context: Client, + deploymentId: string, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsResponseObjectOptions = { + requestOptions: {}, + }, +): StreamableMethod< + | GetAudioTranscriptionAsResponseObject200Response + | GetAudioTranscriptionAsResponseObjectDefaultResponse +> { + return context.path("/deployments/{deploymentId}/audio/transcriptions", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + contentType: (options.contentType as any) ?? "multipart/form-data", + body: { + file: uint8ArrayToString(body["file"], "base64"), + filename: body["filename"], + response_format: body["responseFormat"], + language: body["language"], + prompt: body["prompt"], + temperature: body["temperature"], + model: body["model"], + }, + }) as StreamableMethod< + | GetAudioTranscriptionAsResponseObject200Response + | GetAudioTranscriptionAsResponseObjectDefaultResponse + >; +} + +export async function _getAudioTranscriptionAsResponseObjectDeserialize( + result: + | GetAudioTranscriptionAsResponseObject200Response + | GetAudioTranscriptionAsResponseObjectDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + text: result.body["text"], + task: result.body["task"], + language: result.body["language"], + duration: result.body["duration"], + segments: + result.body["segments"] === undefined + ? result.body["segments"] + : result.body["segments"].map((p) => ({ + id: p["id"], + start: p["start"], + end: p["end"], + text: p["text"], + temperature: p["temperature"], + avgLogprob: p["avg_logprob"], + compressionRatio: p["compression_ratio"], + noSpeechProb: p["no_speech_prob"], + tokens: p["tokens"], + seek: p["seek"], + })), + }; +} + +/** + * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the + * written language corresponding to the language it was spoken in. + */ +export async function getAudioTranscriptionAsResponseObject( + context: Client, + deploymentId: string, + body: AudioTranscriptionOptions, + options: GetAudioTranscriptionAsResponseObjectOptions = { + requestOptions: {}, + }, +): Promise { + const result = await _getAudioTranscriptionAsResponseObjectSend( + context, + deploymentId, + body, + options, + ); + return _getAudioTranscriptionAsResponseObjectDeserialize(result); +} + +export function _getAudioTranslationAsPlainTextSend( + context: Client, + deploymentId: string, + body: AudioTranslationOptions, + options: GetAudioTranslationAsPlainTextOptions = { requestOptions: {} }, +): StreamableMethod< + GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsPlainTextDefaultResponse +> { + return context.path("/deployments/{deploymentId}/audio/translations", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { + file: uint8ArrayToString(body["file"], "base64"), + filename: body["filename"], + response_format: body["responseFormat"], + prompt: body["prompt"], + temperature: body["temperature"], + model: body["model"], + }, + }) as StreamableMethod< + GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsPlainTextDefaultResponse + >; +} + +export async function _getAudioTranslationAsPlainTextDeserialize( + result: GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsPlainTextDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return result.body; +} + +/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ +export async function getAudioTranslationAsPlainText( + context: Client, + deploymentId: string, + body: AudioTranslationOptions, + options: GetAudioTranslationAsPlainTextOptions = { requestOptions: {} }, +): Promise { + const result = await _getAudioTranslationAsPlainTextSend(context, deploymentId, body, options); + return _getAudioTranslationAsPlainTextDeserialize(result); +} + +export function _getAudioTranslationAsResponseObjectSend( + context: Client, + deploymentId: string, + body: AudioTranslationOptions, + options: GetAudioTranslationAsResponseObjectOptions = { requestOptions: {} }, +): StreamableMethod< + | GetAudioTranslationAsResponseObject200Response + | GetAudioTranslationAsResponseObjectDefaultResponse +> { + return context.path("/deployments/{deploymentId}/audio/translations", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + contentType: (options.contentType as any) ?? "multipart/form-data", + body: { + file: uint8ArrayToString(body["file"], "base64"), + filename: body["filename"], + response_format: body["responseFormat"], + prompt: body["prompt"], + temperature: body["temperature"], + model: body["model"], + }, + }) as StreamableMethod< + | GetAudioTranslationAsResponseObject200Response + | GetAudioTranslationAsResponseObjectDefaultResponse + >; +} + +export async function _getAudioTranslationAsResponseObjectDeserialize( + result: + | GetAudioTranslationAsResponseObject200Response + | GetAudioTranslationAsResponseObjectDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + text: result.body["text"], + task: result.body["task"], + language: result.body["language"], + duration: result.body["duration"], + segments: + result.body["segments"] === undefined + ? result.body["segments"] + : result.body["segments"].map((p) => ({ + id: p["id"], + start: p["start"], + end: p["end"], + text: p["text"], + temperature: p["temperature"], + avgLogprob: p["avg_logprob"], + compressionRatio: p["compression_ratio"], + noSpeechProb: p["no_speech_prob"], + tokens: p["tokens"], + seek: p["seek"], + })), + }; +} + +/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ +export async function getAudioTranslationAsResponseObject( + context: Client, + deploymentId: string, + body: AudioTranslationOptions, + options: GetAudioTranslationAsResponseObjectOptions = { requestOptions: {} }, +): Promise { + const result = await _getAudioTranslationAsResponseObjectSend( + context, + deploymentId, + body, + options, + ); + return _getAudioTranslationAsResponseObjectDeserialize(result); +} + +export function _getCompletionsSend( + context: Client, + deploymentId: string, + body: CompletionsOptions, + options: GetCompletionsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/completions", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { + prompt: body["prompt"], + max_tokens: body["maxTokens"], + temperature: body["temperature"], + top_p: body["topP"], + logit_bias: body["logitBias"], + user: body["user"], + n: body["n"], + logprobs: body["logprobs"], + echo: body["echo"], + stop: body["stop"], + presence_penalty: body["presencePenalty"], + frequency_penalty: body["frequencyPenalty"], + best_of: body["bestOf"], + stream: body["stream"], + model: body["model"], + }, + }); +} + +export async function _getCompletionsDeserialize( + result: GetCompletions200Response | GetCompletionsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + id: result.body["id"], + created: new Date(result.body["created"]), + promptFilterResults: + result.body["prompt_filter_results"] === undefined + ? result.body["prompt_filter_results"] + : result.body["prompt_filter_results"].map((p) => ({ + promptIndex: p["prompt_index"], + contentFilterResults: { + sexual: !p.content_filter_results.sexual + ? undefined + : { + severity: p.content_filter_results.sexual?.["severity"], + filtered: p.content_filter_results.sexual?.["filtered"], + }, + violence: !p.content_filter_results.violence + ? undefined + : { + severity: p.content_filter_results.violence?.["severity"], + filtered: p.content_filter_results.violence?.["filtered"], + }, + hate: !p.content_filter_results.hate + ? undefined + : { + severity: p.content_filter_results.hate?.["severity"], + filtered: p.content_filter_results.hate?.["filtered"], + }, + selfHarm: !p.content_filter_results.self_harm + ? undefined + : { + severity: p.content_filter_results.self_harm?.["severity"], + filtered: p.content_filter_results.self_harm?.["filtered"], + }, + profanity: !p.content_filter_results.profanity + ? undefined + : { + filtered: p.content_filter_results.profanity?.["filtered"], + detected: p.content_filter_results.profanity?.["detected"], + }, + customBlocklists: + p.content_filter_results["custom_blocklists"] === undefined + ? p.content_filter_results["custom_blocklists"] + : p.content_filter_results["custom_blocklists"].map((p) => ({ + id: p["id"], + filtered: p["filtered"], + })), + error: !p.content_filter_results.error ? undefined : p.content_filter_results.error, + jailbreak: !p.content_filter_results.jailbreak + ? undefined + : { + filtered: p.content_filter_results.jailbreak?.["filtered"], + detected: p.content_filter_results.jailbreak?.["detected"], + }, + }, + })), + choices: result.body["choices"].map((p) => ({ + text: p["text"], + index: p["index"], + contentFilterResults: !p.content_filter_results + ? undefined + : { + sexual: !p.content_filter_results?.sexual + ? undefined + : { + severity: p.content_filter_results?.sexual?.["severity"], + filtered: p.content_filter_results?.sexual?.["filtered"], + }, + violence: !p.content_filter_results?.violence + ? undefined + : { + severity: p.content_filter_results?.violence?.["severity"], + filtered: p.content_filter_results?.violence?.["filtered"], + }, + hate: !p.content_filter_results?.hate + ? undefined + : { + severity: p.content_filter_results?.hate?.["severity"], + filtered: p.content_filter_results?.hate?.["filtered"], + }, + selfHarm: !p.content_filter_results?.self_harm + ? undefined + : { + severity: p.content_filter_results?.self_harm?.["severity"], + filtered: p.content_filter_results?.self_harm?.["filtered"], + }, + profanity: !p.content_filter_results?.profanity + ? undefined + : { + filtered: p.content_filter_results?.profanity?.["filtered"], + detected: p.content_filter_results?.profanity?.["detected"], + }, + customBlocklists: + p.content_filter_results?.["custom_blocklists"] === undefined + ? p.content_filter_results?.["custom_blocklists"] + : p.content_filter_results?.["custom_blocklists"].map((p) => ({ + id: p["id"], + filtered: p["filtered"], + })), + error: !p.content_filter_results?.error ? undefined : p.content_filter_results?.error, + protectedMaterialText: !p.content_filter_results?.protected_material_text + ? undefined + : { + filtered: p.content_filter_results?.protected_material_text?.["filtered"], + detected: p.content_filter_results?.protected_material_text?.["detected"], + }, + protectedMaterialCode: !p.content_filter_results?.protected_material_code + ? undefined + : { + filtered: p.content_filter_results?.protected_material_code?.["filtered"], + detected: p.content_filter_results?.protected_material_code?.["detected"], + url: p.content_filter_results?.protected_material_code?.["URL"], + license: p.content_filter_results?.protected_material_code?.["license"], + }, + }, + logprobs: + p.logprobs === null + ? null + : { + tokens: p.logprobs["tokens"], + tokenLogprobs: p.logprobs["token_logprobs"], + topLogprobs: p.logprobs["top_logprobs"], + textOffset: p.logprobs["text_offset"], + }, + finishReason: p["finish_reason"], + })), + usage: { + completionTokens: result.body.usage["completion_tokens"], + promptTokens: result.body.usage["prompt_tokens"], + totalTokens: result.body.usage["total_tokens"], + }, + }; +} + +/** + * Gets completions for the provided input prompts. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ +export async function getCompletions( + context: Client, + deploymentId: string, + body: CompletionsOptions, + options: GetCompletionsOptions = { requestOptions: {} }, +): Promise { + const result = await _getCompletionsSend(context, deploymentId, body, options); + return _getCompletionsDeserialize(result); +} + +export function _getChatCompletionsSend( + context: Client, + deploymentId: string, + body: ChatCompletionsOptions, + options: GetChatCompletionsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/chat/completions", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { + messages: body["messages"].map((p) => serializeChatRequestMessageUnion(p)), + functions: + body["functions"] === undefined + ? body["functions"] + : body["functions"].map((p) => ({ + name: p["name"], + description: p["description"], + parameters: p["parameters"], + })), + function_call: body["functionCall"], + max_tokens: body["maxTokens"], + temperature: body["temperature"], + top_p: body["topP"], + logit_bias: body["logitBias"], + user: body["user"], + n: body["n"], + stop: body["stop"], + presence_penalty: body["presencePenalty"], + frequency_penalty: body["frequencyPenalty"], + stream: body["stream"], + model: body["model"], + dataSources: body["dataSources"], + enhancements: !body.enhancements + ? undefined + : { + grounding: !body.enhancements?.grounding + ? undefined + : { enabled: body.enhancements?.grounding?.["enabled"] }, + ocr: !body.enhancements?.ocr + ? undefined + : { enabled: body.enhancements?.ocr?.["enabled"] }, + }, + seed: body["seed"], + response_format: !body.responseFormat ? undefined : { type: body.responseFormat?.["type"] }, + tools: body["tools"], + tool_choice: body["toolChoice"], + }, + }); +} + +export async function _getChatCompletionsDeserialize( + result: GetChatCompletions200Response | GetChatCompletionsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + id: result.body["id"], + created: new Date(result.body["created"]), + choices: result.body["choices"].map((p) => ({ + message: !p.message + ? undefined + : { + role: p.message?.["role"], + content: p.message?.["content"], + toolCalls: + p.message?.["tool_calls"] === undefined + ? p.message?.["tool_calls"] + : p.message?.["tool_calls"], + functionCall: !p.message?.function_call + ? undefined + : { + name: p.message?.function_call?.["name"], + arguments: p.message?.function_call?.["arguments"], + }, + context: !p.message?.context + ? undefined + : { + messages: + p.message?.context?.["messages"] === undefined + ? p.message?.context?.["messages"] + : p.message?.context?.["messages"].map((p) => ({ + role: p["role"], + content: p["content"], + toolCalls: + p["tool_calls"] === undefined ? p["tool_calls"] : p["tool_calls"], + functionCall: !p.function_call + ? undefined + : { + name: p.function_call?.["name"], + arguments: p.function_call?.["arguments"], + }, + context: !p.context ? undefined : (p.context as any), + })), + }, + }, + index: p["index"], + finishReason: p["finish_reason"], + finishDetails: !p.finish_details ? undefined : { type: p.finish_details?.["type"] }, + delta: !p.delta + ? undefined + : { + role: p.delta?.["role"], + content: p.delta?.["content"], + toolCalls: + p.delta?.["tool_calls"] === undefined + ? p.delta?.["tool_calls"] + : p.delta?.["tool_calls"], + functionCall: !p.delta?.function_call + ? undefined + : { + name: p.delta?.function_call?.["name"], + arguments: p.delta?.function_call?.["arguments"], + }, + context: !p.delta?.context + ? undefined + : { + messages: + p.delta?.context?.["messages"] === undefined + ? p.delta?.context?.["messages"] + : p.delta?.context?.["messages"].map((p) => ({ + role: p["role"], + content: p["content"], + toolCalls: + p["tool_calls"] === undefined ? p["tool_calls"] : p["tool_calls"], + functionCall: !p.function_call + ? undefined + : { + name: p.function_call?.["name"], + arguments: p.function_call?.["arguments"], + }, + context: !p.context ? undefined : (p.context as any), + })), + }, + }, + contentFilterResults: !p.content_filter_results + ? undefined + : { + sexual: !p.content_filter_results?.sexual + ? undefined + : { + severity: p.content_filter_results?.sexual?.["severity"], + filtered: p.content_filter_results?.sexual?.["filtered"], + }, + violence: !p.content_filter_results?.violence + ? undefined + : { + severity: p.content_filter_results?.violence?.["severity"], + filtered: p.content_filter_results?.violence?.["filtered"], + }, + hate: !p.content_filter_results?.hate + ? undefined + : { + severity: p.content_filter_results?.hate?.["severity"], + filtered: p.content_filter_results?.hate?.["filtered"], + }, + selfHarm: !p.content_filter_results?.self_harm + ? undefined + : { + severity: p.content_filter_results?.self_harm?.["severity"], + filtered: p.content_filter_results?.self_harm?.["filtered"], + }, + profanity: !p.content_filter_results?.profanity + ? undefined + : { + filtered: p.content_filter_results?.profanity?.["filtered"], + detected: p.content_filter_results?.profanity?.["detected"], + }, + customBlocklists: + p.content_filter_results?.["custom_blocklists"] === undefined + ? p.content_filter_results?.["custom_blocklists"] + : p.content_filter_results?.["custom_blocklists"].map((p) => ({ + id: p["id"], + filtered: p["filtered"], + })), + error: !p.content_filter_results?.error ? undefined : p.content_filter_results?.error, + protectedMaterialText: !p.content_filter_results?.protected_material_text + ? undefined + : { + filtered: p.content_filter_results?.protected_material_text?.["filtered"], + detected: p.content_filter_results?.protected_material_text?.["detected"], + }, + protectedMaterialCode: !p.content_filter_results?.protected_material_code + ? undefined + : { + filtered: p.content_filter_results?.protected_material_code?.["filtered"], + detected: p.content_filter_results?.protected_material_code?.["detected"], + url: p.content_filter_results?.protected_material_code?.["URL"], + license: p.content_filter_results?.protected_material_code?.["license"], + }, + }, + enhancements: !p.enhancements + ? undefined + : { + grounding: !p.enhancements?.grounding + ? undefined + : { + lines: p.enhancements?.grounding?.["lines"].map((p) => ({ + text: p["text"], + spans: p["spans"].map((p) => ({ + text: p["text"], + offset: p["offset"], + length: p["length"], + polygon: p["polygon"].map((p) => ({ + x: p["x"], + y: p["y"], + })), + })), + })), + }, + }, + })), + promptFilterResults: + result.body["prompt_filter_results"] === undefined + ? result.body["prompt_filter_results"] + : result.body["prompt_filter_results"].map((p) => ({ + promptIndex: p["prompt_index"], + contentFilterResults: { + sexual: !p.content_filter_results.sexual + ? undefined + : { + severity: p.content_filter_results.sexual?.["severity"], + filtered: p.content_filter_results.sexual?.["filtered"], + }, + violence: !p.content_filter_results.violence + ? undefined + : { + severity: p.content_filter_results.violence?.["severity"], + filtered: p.content_filter_results.violence?.["filtered"], + }, + hate: !p.content_filter_results.hate + ? undefined + : { + severity: p.content_filter_results.hate?.["severity"], + filtered: p.content_filter_results.hate?.["filtered"], + }, + selfHarm: !p.content_filter_results.self_harm + ? undefined + : { + severity: p.content_filter_results.self_harm?.["severity"], + filtered: p.content_filter_results.self_harm?.["filtered"], + }, + profanity: !p.content_filter_results.profanity + ? undefined + : { + filtered: p.content_filter_results.profanity?.["filtered"], + detected: p.content_filter_results.profanity?.["detected"], + }, + customBlocklists: + p.content_filter_results["custom_blocklists"] === undefined + ? p.content_filter_results["custom_blocklists"] + : p.content_filter_results["custom_blocklists"].map((p) => ({ + id: p["id"], + filtered: p["filtered"], + })), + error: !p.content_filter_results.error ? undefined : p.content_filter_results.error, + jailbreak: !p.content_filter_results.jailbreak + ? undefined + : { + filtered: p.content_filter_results.jailbreak?.["filtered"], + detected: p.content_filter_results.jailbreak?.["detected"], + }, + }, + })), + systemFingerprint: result.body["system_fingerprint"], + usage: { + completionTokens: result.body.usage["completion_tokens"], + promptTokens: result.body.usage["prompt_tokens"], + totalTokens: result.body.usage["total_tokens"], + }, + }; +} + +/** + * Gets chat completions for the provided chat messages. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ +export async function getChatCompletions( + context: Client, + deploymentId: string, + body: ChatCompletionsOptions, + options: GetChatCompletionsOptions = { requestOptions: {} }, +): Promise { + const result = await _getChatCompletionsSend(context, deploymentId, body, options); + return _getChatCompletionsDeserialize(result); +} + +export function _getChatCompletionsWithAzureExtensionsSend( + context: Client, + deploymentId: string, + body: ChatCompletionsOptions, + options: GetChatCompletionsWithAzureExtensionsOptions = { + requestOptions: {}, + }, +): StreamableMethod< + | GetChatCompletionsWithAzureExtensions200Response + | GetChatCompletionsWithAzureExtensionsDefaultResponse +> { + return context + .path("/deployments/{deploymentId}/extensions/chat/completions", deploymentId) + .post({ + ...operationOptionsToRequestParameters(options), + body: { + messages: body["messages"].map((p) => serializeChatRequestMessageUnion(p)), + functions: + body["functions"] === undefined + ? body["functions"] + : body["functions"].map((p) => ({ + name: p["name"], + description: p["description"], + parameters: p["parameters"], + })), + function_call: body["functionCall"], + max_tokens: body["maxTokens"], + temperature: body["temperature"], + top_p: body["topP"], + logit_bias: body["logitBias"], + user: body["user"], + n: body["n"], + stop: body["stop"], + presence_penalty: body["presencePenalty"], + frequency_penalty: body["frequencyPenalty"], + stream: body["stream"], + model: body["model"], + dataSources: body["dataSources"], + enhancements: !body.enhancements + ? undefined + : { + grounding: !body.enhancements?.grounding + ? undefined + : { enabled: body.enhancements?.grounding?.["enabled"] }, + ocr: !body.enhancements?.ocr + ? undefined + : { enabled: body.enhancements?.ocr?.["enabled"] }, + }, + seed: body["seed"], + response_format: !body.responseFormat ? undefined : { type: body.responseFormat?.["type"] }, + tools: body["tools"], + tool_choice: body["toolChoice"], + }, + }); +} + +export async function _getChatCompletionsWithAzureExtensionsDeserialize( + result: + | GetChatCompletionsWithAzureExtensions200Response + | GetChatCompletionsWithAzureExtensionsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + id: result.body["id"], + created: new Date(result.body["created"]), + choices: result.body["choices"].map((p) => ({ + message: !p.message + ? undefined + : { + role: p.message?.["role"], + content: p.message?.["content"], + toolCalls: + p.message?.["tool_calls"] === undefined + ? p.message?.["tool_calls"] + : p.message?.["tool_calls"], + functionCall: !p.message?.function_call + ? undefined + : { + name: p.message?.function_call?.["name"], + arguments: p.message?.function_call?.["arguments"], + }, + context: !p.message?.context + ? undefined + : { + messages: + p.message?.context?.["messages"] === undefined + ? p.message?.context?.["messages"] + : p.message?.context?.["messages"].map((p) => ({ + role: p["role"], + content: p["content"], + toolCalls: + p["tool_calls"] === undefined ? p["tool_calls"] : p["tool_calls"], + functionCall: !p.function_call + ? undefined + : { + name: p.function_call?.["name"], + arguments: p.function_call?.["arguments"], + }, + context: !p.context ? undefined : (p.context as any), + })), + }, + }, + index: p["index"], + finishReason: p["finish_reason"], + finishDetails: !p.finish_details ? undefined : { type: p.finish_details?.["type"] }, + delta: !p.delta + ? undefined + : { + role: p.delta?.["role"], + content: p.delta?.["content"], + toolCalls: + p.delta?.["tool_calls"] === undefined + ? p.delta?.["tool_calls"] + : p.delta?.["tool_calls"], + functionCall: !p.delta?.function_call + ? undefined + : { + name: p.delta?.function_call?.["name"], + arguments: p.delta?.function_call?.["arguments"], + }, + context: !p.delta?.context + ? undefined + : { + messages: + p.delta?.context?.["messages"] === undefined + ? p.delta?.context?.["messages"] + : p.delta?.context?.["messages"].map((p) => ({ + role: p["role"], + content: p["content"], + toolCalls: + p["tool_calls"] === undefined ? p["tool_calls"] : p["tool_calls"], + functionCall: !p.function_call + ? undefined + : { + name: p.function_call?.["name"], + arguments: p.function_call?.["arguments"], + }, + context: !p.context ? undefined : (p.context as any), + })), + }, + }, + contentFilterResults: !p.content_filter_results + ? undefined + : { + sexual: !p.content_filter_results?.sexual + ? undefined + : { + severity: p.content_filter_results?.sexual?.["severity"], + filtered: p.content_filter_results?.sexual?.["filtered"], + }, + violence: !p.content_filter_results?.violence + ? undefined + : { + severity: p.content_filter_results?.violence?.["severity"], + filtered: p.content_filter_results?.violence?.["filtered"], + }, + hate: !p.content_filter_results?.hate + ? undefined + : { + severity: p.content_filter_results?.hate?.["severity"], + filtered: p.content_filter_results?.hate?.["filtered"], + }, + selfHarm: !p.content_filter_results?.self_harm + ? undefined + : { + severity: p.content_filter_results?.self_harm?.["severity"], + filtered: p.content_filter_results?.self_harm?.["filtered"], + }, + profanity: !p.content_filter_results?.profanity + ? undefined + : { + filtered: p.content_filter_results?.profanity?.["filtered"], + detected: p.content_filter_results?.profanity?.["detected"], + }, + customBlocklists: + p.content_filter_results?.["custom_blocklists"] === undefined + ? p.content_filter_results?.["custom_blocklists"] + : p.content_filter_results?.["custom_blocklists"].map((p) => ({ + id: p["id"], + filtered: p["filtered"], + })), + error: !p.content_filter_results?.error ? undefined : p.content_filter_results?.error, + protectedMaterialText: !p.content_filter_results?.protected_material_text + ? undefined + : { + filtered: p.content_filter_results?.protected_material_text?.["filtered"], + detected: p.content_filter_results?.protected_material_text?.["detected"], + }, + protectedMaterialCode: !p.content_filter_results?.protected_material_code + ? undefined + : { + filtered: p.content_filter_results?.protected_material_code?.["filtered"], + detected: p.content_filter_results?.protected_material_code?.["detected"], + url: p.content_filter_results?.protected_material_code?.["URL"], + license: p.content_filter_results?.protected_material_code?.["license"], + }, + }, + enhancements: !p.enhancements + ? undefined + : { + grounding: !p.enhancements?.grounding + ? undefined + : { + lines: p.enhancements?.grounding?.["lines"].map((p) => ({ + text: p["text"], + spans: p["spans"].map((p) => ({ + text: p["text"], + offset: p["offset"], + length: p["length"], + polygon: p["polygon"].map((p) => ({ + x: p["x"], + y: p["y"], + })), + })), + })), + }, + }, + })), + promptFilterResults: + result.body["prompt_filter_results"] === undefined + ? result.body["prompt_filter_results"] + : result.body["prompt_filter_results"].map((p) => ({ + promptIndex: p["prompt_index"], + contentFilterResults: { + sexual: !p.content_filter_results.sexual + ? undefined + : { + severity: p.content_filter_results.sexual?.["severity"], + filtered: p.content_filter_results.sexual?.["filtered"], + }, + violence: !p.content_filter_results.violence + ? undefined + : { + severity: p.content_filter_results.violence?.["severity"], + filtered: p.content_filter_results.violence?.["filtered"], + }, + hate: !p.content_filter_results.hate + ? undefined + : { + severity: p.content_filter_results.hate?.["severity"], + filtered: p.content_filter_results.hate?.["filtered"], + }, + selfHarm: !p.content_filter_results.self_harm + ? undefined + : { + severity: p.content_filter_results.self_harm?.["severity"], + filtered: p.content_filter_results.self_harm?.["filtered"], + }, + profanity: !p.content_filter_results.profanity + ? undefined + : { + filtered: p.content_filter_results.profanity?.["filtered"], + detected: p.content_filter_results.profanity?.["detected"], + }, + customBlocklists: + p.content_filter_results["custom_blocklists"] === undefined + ? p.content_filter_results["custom_blocklists"] + : p.content_filter_results["custom_blocklists"].map((p) => ({ + id: p["id"], + filtered: p["filtered"], + })), + error: !p.content_filter_results.error ? undefined : p.content_filter_results.error, + jailbreak: !p.content_filter_results.jailbreak + ? undefined + : { + filtered: p.content_filter_results.jailbreak?.["filtered"], + detected: p.content_filter_results.jailbreak?.["detected"], + }, + }, + })), + systemFingerprint: result.body["system_fingerprint"], + usage: { + completionTokens: result.body.usage["completion_tokens"], + promptTokens: result.body.usage["prompt_tokens"], + totalTokens: result.body.usage["total_tokens"], + }, + }; +} + +/** + * Gets chat completions for the provided chat messages. + * This is an Azure-specific version of chat completions that supports integration with configured data sources and + * other augmentations to the base chat completions capabilities. + */ +export async function getChatCompletionsWithAzureExtensions( + context: Client, + deploymentId: string, + body: ChatCompletionsOptions, + options: GetChatCompletionsWithAzureExtensionsOptions = { + requestOptions: {}, + }, +): Promise { + const result = await _getChatCompletionsWithAzureExtensionsSend( + context, + deploymentId, + body, + options, + ); + return _getChatCompletionsWithAzureExtensionsDeserialize(result); +} + +export function _getImageGenerationsSend( + context: Client, + deploymentId: string, + body: ImageGenerationOptions, + options: GetImageGenerationsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/images/generations", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { + model: body["model"], + prompt: body["prompt"], + n: body["n"], + size: body["size"], + response_format: body["responseFormat"], + quality: body["quality"], + style: body["style"], + user: body["user"], + }, + }); +} + +export async function _getImageGenerationsDeserialize( + result: GetImageGenerations200Response | GetImageGenerationsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + created: new Date(result.body["created"]), + data: result.body["data"].map((p) => ({ + url: p["url"], + base64Data: p["b64_json"], + revisedPrompt: p["revised_prompt"], + })), + }; +} + +/** Creates an image given a prompt. */ +export async function getImageGenerations( + context: Client, + deploymentId: string, + body: ImageGenerationOptions, + options: GetImageGenerationsOptions = { requestOptions: {} }, +): Promise { + const result = await _getImageGenerationsSend(context, deploymentId, body, options); + return _getImageGenerationsDeserialize(result); +} + +export function _getEmbeddingsSend( + context: Client, + deploymentId: string, + body: EmbeddingsOptions, + options: GetEmbeddingsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/embeddings", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { user: body["user"], model: body["model"], input: body["input"] }, + }); +} + +export async function _getEmbeddingsDeserialize( + result: GetEmbeddings200Response | GetEmbeddingsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw createRestError(result); + } + + return { + data: result.body["data"].map((p) => ({ + embedding: p["embedding"], + index: p["index"], + })), + usage: { + promptTokens: result.body.usage["prompt_tokens"], + totalTokens: result.body.usage["total_tokens"], + }, + }; +} + +/** Return the embeddings for a given prompt. */ +export async function getEmbeddings( + context: Client, + deploymentId: string, + body: EmbeddingsOptions, + options: GetEmbeddingsOptions = { requestOptions: {} }, +): Promise { + const result = await _getEmbeddingsSend(context, deploymentId, body, options); + return _getEmbeddingsDeserialize(result); +} diff --git a/sdk/openai/openai/sources/generated/src/index.ts b/sdk/openai/openai/generated/index.ts similarity index 58% rename from sdk/openai/openai/sources/generated/src/index.ts rename to sdk/openai/openai/generated/index.ts index a7681ca770aa..f615a56c8fa5 100644 --- a/sdk/openai/openai/sources/generated/src/index.ts +++ b/sdk/openai/openai/generated/index.ts @@ -28,44 +28,71 @@ export { CompletionsUsage, ChatCompletionsOptions, ChatRequestMessage, - ChatRole, + ChatRequestSystemMessage, + ChatRequestUserMessage, ChatMessageContentItem, + ChatMessageTextContentItem, + ChatMessageImageContentItem, ChatMessageImageUrl, ChatMessageImageDetailLevel, + ChatRequestAssistantMessage, ChatCompletionsToolCall, + ChatCompletionsFunctionToolCall, FunctionCall, + ChatRequestToolMessage, + ChatRequestFunctionMessage, + ChatRole, FunctionDefinition, FunctionCallPreset, FunctionName, AzureChatExtensionConfiguration, - AzureChatExtensionType, + AzureCognitiveSearchChatExtensionConfiguration, AzureCognitiveSearchChatExtensionParameters, OnYourDataAuthenticationOptions, + OnYourDataApiKeyAuthenticationOptions, + OnYourDataConnectionStringAuthenticationOptions, + OnYourDataKeyAndKeyIdAuthenticationOptions, + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, + OnYourDataUserAssignedManagedIdentityAuthenticationOptions, OnYourDataAuthenticationType, AzureCognitiveSearchIndexFieldMappingOptions, AzureCognitiveSearchQueryType, OnYourDataVectorizationSource, + OnYourDataEndpointVectorizationSource, + OnYourDataDeploymentNameVectorizationSource, + OnYourDataModelIdVectorizationSource, OnYourDataVectorizationSourceType, + AzureMachineLearningIndexChatExtensionConfiguration, AzureMachineLearningIndexChatExtensionParameters, + AzureCosmosDBChatExtensionConfiguration, AzureCosmosDBChatExtensionParameters, AzureCosmosDBFieldMappingOptions, + ElasticsearchChatExtensionConfiguration, ElasticsearchChatExtensionParameters, ElasticsearchIndexFieldMappingOptions, ElasticsearchQueryType, + PineconeChatExtensionConfiguration, PineconeChatExtensionParameters, PineconeFieldMappingOptions, + AzureChatExtensionType, AzureChatEnhancementConfiguration, AzureChatGroundingEnhancementConfiguration, AzureChatOCREnhancementConfiguration, ChatCompletionsResponseFormat, + ChatCompletionsTextResponseFormat, + ChatCompletionsJsonResponseFormat, ChatCompletionsToolDefinition, + ChatCompletionsFunctionToolDefinition, ChatCompletionsToolSelectionPreset, ChatCompletionsNamedToolSelection, + ChatCompletionsNamedFunctionToolSelection, ChatCompletions, ChatChoice, ChatResponseMessage, AzureChatExtensionsMessageContext, ChatFinishDetails, + StopFinishDetails, + MaxTokensFinishDetails, AzureChatEnhancements, AzureGroundingEnhancement, AzureGroundingEnhancementLine, @@ -82,17 +109,23 @@ export { Embeddings, EmbeddingItem, EmbeddingsUsage, - ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ClientOpenAIClientGetCompletionsOptions, - ClientOpenAIClientGetChatCompletionsOptions, - ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ClientOpenAIClientGetImageGenerationsOptions, - ClientOpenAIClientGetEmbeddingsOptions, + ChatRequestMessageUnion, + ChatMessageContentItemUnion, + ChatCompletionsToolCallUnion, + AzureChatExtensionConfigurationUnion, + OnYourDataAuthenticationOptionsUnion, + OnYourDataVectorizationSourceUnion, + ChatCompletionsResponseFormatUnion, + ChatCompletionsToolDefinitionUnion, + ChatCompletionsNamedToolSelectionUnion, + ChatFinishDetailsUnion, + GetAudioTranscriptionAsPlainTextOptions, + GetAudioTranscriptionAsResponseObjectOptions, + GetAudioTranslationAsPlainTextOptions, + GetAudioTranslationAsResponseObjectOptions, + GetCompletionsOptions, + GetChatCompletionsOptions, + GetChatCompletionsWithAzureExtensionsOptions, + GetImageGenerationsOptions, + GetEmbeddingsOptions, } from "./models/index.js"; -export { - ClientOperations, - ClientOpenAIClientOperations, -} from "./classic/index.js"; diff --git a/sdk/openai/openai/sources/generated/src/logger.ts b/sdk/openai/openai/generated/logger.ts similarity index 100% rename from sdk/openai/openai/sources/generated/src/logger.ts rename to sdk/openai/openai/generated/logger.ts diff --git a/sdk/openai/openai/sources/generated/src/models/index.ts b/sdk/openai/openai/generated/models/index.ts similarity index 57% rename from sdk/openai/openai/sources/generated/src/models/index.ts rename to sdk/openai/openai/generated/models/index.ts index a6ad5c023fec..5e0d7e88739d 100644 --- a/sdk/openai/openai/sources/generated/src/models/index.ts +++ b/sdk/openai/openai/generated/models/index.ts @@ -27,44 +27,71 @@ export { CompletionsUsage, ChatCompletionsOptions, ChatRequestMessage, - ChatRole, + ChatRequestSystemMessage, + ChatRequestUserMessage, ChatMessageContentItem, + ChatMessageTextContentItem, + ChatMessageImageContentItem, ChatMessageImageUrl, ChatMessageImageDetailLevel, + ChatRequestAssistantMessage, ChatCompletionsToolCall, + ChatCompletionsFunctionToolCall, FunctionCall, + ChatRequestToolMessage, + ChatRequestFunctionMessage, + ChatRole, FunctionDefinition, FunctionCallPreset, FunctionName, AzureChatExtensionConfiguration, - AzureChatExtensionType, + AzureCognitiveSearchChatExtensionConfiguration, AzureCognitiveSearchChatExtensionParameters, OnYourDataAuthenticationOptions, + OnYourDataApiKeyAuthenticationOptions, + OnYourDataConnectionStringAuthenticationOptions, + OnYourDataKeyAndKeyIdAuthenticationOptions, + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, + OnYourDataUserAssignedManagedIdentityAuthenticationOptions, OnYourDataAuthenticationType, AzureCognitiveSearchIndexFieldMappingOptions, AzureCognitiveSearchQueryType, OnYourDataVectorizationSource, + OnYourDataEndpointVectorizationSource, + OnYourDataDeploymentNameVectorizationSource, + OnYourDataModelIdVectorizationSource, OnYourDataVectorizationSourceType, + AzureMachineLearningIndexChatExtensionConfiguration, AzureMachineLearningIndexChatExtensionParameters, + AzureCosmosDBChatExtensionConfiguration, AzureCosmosDBChatExtensionParameters, AzureCosmosDBFieldMappingOptions, + ElasticsearchChatExtensionConfiguration, ElasticsearchChatExtensionParameters, ElasticsearchIndexFieldMappingOptions, ElasticsearchQueryType, + PineconeChatExtensionConfiguration, PineconeChatExtensionParameters, PineconeFieldMappingOptions, + AzureChatExtensionType, AzureChatEnhancementConfiguration, AzureChatGroundingEnhancementConfiguration, AzureChatOCREnhancementConfiguration, ChatCompletionsResponseFormat, + ChatCompletionsTextResponseFormat, + ChatCompletionsJsonResponseFormat, ChatCompletionsToolDefinition, + ChatCompletionsFunctionToolDefinition, ChatCompletionsToolSelectionPreset, ChatCompletionsNamedToolSelection, + ChatCompletionsNamedFunctionToolSelection, ChatCompletions, ChatChoice, ChatResponseMessage, AzureChatExtensionsMessageContext, ChatFinishDetails, + StopFinishDetails, + MaxTokensFinishDetails, AzureChatEnhancements, AzureGroundingEnhancement, AzureGroundingEnhancementLine, @@ -81,15 +108,25 @@ export { Embeddings, EmbeddingItem, EmbeddingsUsage, + ChatRequestMessageUnion, + ChatMessageContentItemUnion, + ChatCompletionsToolCallUnion, + AzureChatExtensionConfigurationUnion, + OnYourDataAuthenticationOptionsUnion, + OnYourDataVectorizationSourceUnion, + ChatCompletionsResponseFormatUnion, + ChatCompletionsToolDefinitionUnion, + ChatCompletionsNamedToolSelectionUnion, + ChatFinishDetailsUnion, } from "./models.js"; export { - ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ClientOpenAIClientGetCompletionsOptions, - ClientOpenAIClientGetChatCompletionsOptions, - ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ClientOpenAIClientGetImageGenerationsOptions, - ClientOpenAIClientGetEmbeddingsOptions, + GetAudioTranscriptionAsPlainTextOptions, + GetAudioTranscriptionAsResponseObjectOptions, + GetAudioTranslationAsPlainTextOptions, + GetAudioTranslationAsResponseObjectOptions, + GetCompletionsOptions, + GetChatCompletionsOptions, + GetChatCompletionsWithAzureExtensionsOptions, + GetImageGenerationsOptions, + GetEmbeddingsOptions, } from "./options.js"; diff --git a/sdk/openai/openai/sources/generated/src/models/models.ts b/sdk/openai/openai/generated/models/models.ts similarity index 76% rename from sdk/openai/openai/sources/generated/src/models/models.ts rename to sdk/openai/openai/generated/models/models.ts index 884da18a6f63..02f7b0bf1bad 100644 --- a/sdk/openai/openai/sources/generated/src/models/models.ts +++ b/sdk/openai/openai/generated/models/models.ts @@ -501,7 +501,7 @@ export interface ChatCompletionsOptions { * the behavior of the assistant, followed by alternating messages between the User and * Assistant roles. */ - messages: ChatRequestMessage[]; + messages: ChatRequestMessageUnion[]; /** A list of functions the model may generate JSON inputs for. */ functions?: FunctionDefinition[]; /** @@ -578,7 +578,7 @@ export interface ChatCompletionsOptions { * The configuration entries for Azure OpenAI chat extensions that use them. * This additional specification is only compatible with Azure OpenAI. */ - dataSources?: AzureChatExtensionConfiguration[]; + dataSources?: AzureChatExtensionConfigurationUnion[]; /** If provided, the configuration options for available Azure OpenAI chat enhancements. */ enhancements?: AzureChatEnhancementConfiguration; /** @@ -588,57 +588,121 @@ export interface ChatCompletionsOptions { */ seed?: number; /** An object specifying the format that the model must output. Used to enable JSON mode. */ - responseFormat?: ChatCompletionsResponseFormat; + responseFormat?: ChatCompletionsResponseFormatUnion; /** The available tool definitions that the chat completions request can use, including caller-defined functions. */ - tools?: ChatCompletionsToolDefinition[]; + tools?: ChatCompletionsToolDefinitionUnion[]; /** If specified, the model will configure which of the provided tools it can use for the chat completions response. */ - toolChoice?: - | ChatCompletionsToolSelectionPreset - | ChatCompletionsNamedToolSelection; + toolChoice?: ChatCompletionsToolSelectionPreset | ChatCompletionsNamedToolSelectionUnion; } /** An abstract representation of a chat message as provided in a request. */ export interface ChatRequestMessage { - /** the discriminator possible values system, user, assistant, tool, function */ + /** the discriminator possible values: system, user, assistant, tool, function */ role: ChatRole; } -/** A description of the intended purpose of a message within a chat completions interaction. */ -/** "system", "assistant", "user", "function", "tool" */ -export type ChatRole = string; +/** + * A request chat message containing system instructions that influence how the model will generate a chat completions + * response. + */ +export interface ChatRequestSystemMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'system' for system messages. */ + role: "system"; + /** The contents of the system message. */ + content: string; + /** An optional name for the participant. */ + name?: string; +} + +/** A request chat message representing user input to the assistant. */ +export interface ChatRequestUserMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'user' for user messages. */ + role: "user"; + /** The contents of the user message, with available input types varying by selected model. */ + content: string | ChatMessageContentItemUnion[]; + /** An optional name for the participant. */ + name?: string; +} /** An abstract representation of a structured content item within a chat message. */ export interface ChatMessageContentItem { - /** the discriminator possible values text, image_url */ + /** the discriminator possible values: text, image_url */ type: string; } +/** A structured chat content item containing plain text. */ +export interface ChatMessageTextContentItem extends ChatMessageContentItem { + /** The discriminated object type: always 'text' for this type. */ + type: "text"; + /** The content of the message. */ + text: string; +} + +/** A structured chat content item containing an image reference. */ +export interface ChatMessageImageContentItem extends ChatMessageContentItem { + /** The discriminated object type: always 'image_url' for this type. */ + type: "image_url"; + /** An internet location, which must be accessible to the model,from which the image may be retrieved. */ + imageUrl: ChatMessageImageUrl; +} + /** An internet location from which the model may retrieve an image. */ export interface ChatMessageImageUrl { /** The URL of the image. */ url: string; - /** + /** * The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and * accuracy. - * - * Possible values: auto, low, high */ - detail?: string; + detail?: ChatMessageImageDetailLevel; } /** A representation of the possible image detail levels for image-based chat completions message content. */ /** "auto", "low", "high" */ export type ChatMessageImageDetailLevel = string; +/** A request chat message representing response or action from the assistant. */ +export interface ChatRequestAssistantMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'assistant' for assistant messages. */ + role: "assistant"; + /** The content of the message. */ + content: string | null; + /** An optional name for the participant. */ + name?: string; + /** + * The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + * completions request to resolve as configured. + */ + toolCalls?: ChatCompletionsToolCallUnion[]; + /** + * The function call that must be resolved and have its output appended to subsequent input messages for the chat + * completions request to resolve as configured. + */ + functionCall?: FunctionCall; +} + /** * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested * chat completion. */ export interface ChatCompletionsToolCall { - /** the discriminator possible values function */ + /** the discriminator possible values: function */ type: string; /** The ID of the tool call. */ id: string; + /** The index of the tool call. */ + index?: number; +} + +/** + * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents + * a function invocation needed for a subsequent chat completions request to resolve. + */ +export interface ChatCompletionsFunctionToolCall extends ChatCompletionsToolCall { + /** The type of tool call, in this case always 'function'. */ + type: "function"; + /** The details of the function invocation requested by the tool call. */ + function: FunctionCall; } /** The name and arguments of a function that should be called, as generated by the model. */ @@ -654,6 +718,30 @@ export interface FunctionCall { arguments: string; } +/** A request chat message representing requested output from a configured tool. */ +export interface ChatRequestToolMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'tool' for tool messages. */ + role: "tool"; + /** The content of the message. */ + content: string | null; + /** The ID of the tool call resolved by the provided content. */ + toolCallId: string; +} + +/** A request chat message representing requested output from a configured function. */ +export interface ChatRequestFunctionMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'function' for function messages. */ + role: "function"; + /** The name of the function that was called to produce output. */ + name: string; + /** The output of the function as requested by the function call. */ + content: string | null; +} + +/** A description of the intended purpose of a message within a chat completions interaction. */ +/** "system", "assistant", "user", "function", "tool" */ +export type ChatRole = string; + /** The definition of a caller-specified function that chat completions may invoke in response to matching user input. */ export interface FunctionDefinition { /** The name of the function to be called. */ @@ -689,17 +777,24 @@ export interface FunctionName { * The use of this configuration is compatible only with Azure OpenAI. */ export interface AzureChatExtensionConfiguration { - /** the discriminator possible values AzureCognitiveSearch, AzureMLIndex, AzureCosmosDB, Elasticsearch, Pinecone */ + /** the discriminator possible values: AzureCognitiveSearch, AzureMLIndex, AzureCosmosDB, Elasticsearch, Pinecone */ type: AzureChatExtensionType; } /** - * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat - * completions request that should use Azure OpenAI chat extensions to augment the response behavior. - * The use of this configuration is compatible only with Azure OpenAI. + * A specific representation of configurable options for Azure Cognitive Search when using it as an Azure OpenAI chat + * extension. */ -/** "AzureCognitiveSearch", "AzureMLIndex", "AzureCosmosDB", "Elasticsearch", "Pinecone" */ -export type AzureChatExtensionType = string; +export interface AzureCognitiveSearchChatExtensionConfiguration + extends AzureChatExtensionConfiguration { + /** + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Azure Cognitive Search. + */ + type: "AzureCognitiveSearch"; + /** The parameters to use when configuring Azure Cognitive Search. */ + parameters: AzureCognitiveSearchChatExtensionParameters; +} /** Parameters for Azure Cognitive Search when used as an Azure OpenAI chat extension. */ export interface AzureCognitiveSearchChatExtensionParameters { @@ -710,7 +805,7 @@ export interface AzureCognitiveSearchChatExtensionParameters { * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) * authentication. */ - authentication?: OnYourDataAuthenticationOptions; + authentication?: OnYourDataAuthenticationOptionsUnion; /** The configured top number of documents to feature for the configured query. */ topNDocuments?: number; /** Whether queries should be restricted to use of indexed data. */ @@ -738,15 +833,59 @@ export interface AzureCognitiveSearchChatExtensionParameters { /** When using embeddings, specifies the API key to use with the provided embeddings endpoint. */ embeddingKey?: string; /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + embeddingDependency?: OnYourDataVectorizationSourceUnion; } /** The authentication options for Azure OpenAI On Your Data. */ export interface OnYourDataAuthenticationOptions { - /** the discriminator possible values APIKey, ConnectionString, KeyAndKeyId, SystemAssignedManagedIdentity, UserAssignedManagedIdentity */ + /** the discriminator possible values: APIKey, ConnectionString, KeyAndKeyId, SystemAssignedManagedIdentity, UserAssignedManagedIdentity */ type: OnYourDataAuthenticationType; } +/** The authentication options for Azure OpenAI On Your Data when using an API key. */ +export interface OnYourDataApiKeyAuthenticationOptions extends OnYourDataAuthenticationOptions { + /** The authentication type of API key. */ + type: "APIKey"; + /** The API key to use for authentication. */ + key: string; +} + +/** The authentication options for Azure OpenAI On Your Data when using a connection string. */ +export interface OnYourDataConnectionStringAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of connection string. */ + type: "ConnectionString"; + /** The connection string to use for authentication. */ + connectionString: string; +} + +/** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. */ +export interface OnYourDataKeyAndKeyIdAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of Elasticsearch key and key ID pair. */ + type: "KeyAndKeyId"; + /** The key to use for authentication. */ + key: string; + /** The key ID to use for authentication. */ + keyId: string; +} + +/** The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. */ +export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of system-assigned managed identity. */ + type: "SystemAssignedManagedIdentity"; +} + +/** The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. */ +export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of user-assigned managed identity. */ + type: "UserAssignedManagedIdentity"; + /** The resource ID of the user-assigned managed identity to use for authentication. */ + managedIdentityResourceId: string; +} + /** The authentication types supported with Azure OpenAI On Your Data. */ /** "APIKey", "ConnectionString", "KeyAndKeyId", "SystemAssignedManagedIdentity", "UserAssignedManagedIdentity" */ export type OnYourDataAuthenticationType = string; @@ -775,10 +914,45 @@ export type AzureCognitiveSearchQueryType = string; /** An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ export interface OnYourDataVectorizationSource { - /** the discriminator possible values Endpoint, DeploymentName, ModelId */ + /** the discriminator possible values: Endpoint, DeploymentName, ModelId */ type: OnYourDataVectorizationSourceType; } +/** + * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + * on a public Azure OpenAI endpoint call for embeddings. + */ +export interface OnYourDataEndpointVectorizationSource extends OnYourDataVectorizationSource { + /** The type of vectorization source to use. Always 'Endpoint' for this type. */ + type: "Endpoint"; + /** Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. */ + endpoint: string; + /** Specifies the authentication options to use when retrieving embeddings from the specified endpoint. */ + authentication: OnYourDataAuthenticationOptionsUnion; +} + +/** + * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + * on an internal embeddings model deployment name in the same Azure OpenAI resource. + */ +export interface OnYourDataDeploymentNameVectorizationSource extends OnYourDataVectorizationSource { + /** The type of vectorization source to use. Always 'DeploymentName' for this type. */ + type: "DeploymentName"; + /** The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. */ + deploymentName: string; +} + +/** + * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + * on a search service model ID. Currently only supported by Elasticsearch®. + */ +export interface OnYourDataModelIdVectorizationSource extends OnYourDataVectorizationSource { + /** The type of vectorization source to use. Always 'ModelId' for this type. */ + type: "ModelId"; + /** The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. */ + modelId: string; +} + /** * Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with * vector search. @@ -786,6 +960,21 @@ export interface OnYourDataVectorizationSource { /** "Endpoint", "DeploymentName", "ModelId" */ export type OnYourDataVectorizationSourceType = string; +/** + * A specific representation of configurable options for Azure Machine Learning vector index when using it as an Azure + * OpenAI chat extension. + */ +export interface AzureMachineLearningIndexChatExtensionConfiguration + extends AzureChatExtensionConfiguration { + /** + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Azure Machine Learning vector index. + */ + type: "AzureMLIndex"; + /** The parameters for the Azure Machine Learning vector index chat extension. */ + parameters: AzureMachineLearningIndexChatExtensionParameters; +} + /** Parameters for the Azure Machine Learning vector index chat extension. */ export interface AzureMachineLearningIndexChatExtensionParameters { /** @@ -795,7 +984,7 @@ export interface AzureMachineLearningIndexChatExtensionParameters { * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) * authentication. */ - authentication?: OnYourDataAuthenticationOptions; + authentication?: OnYourDataAuthenticationOptionsUnion; /** The configured top number of documents to feature for the configured query. */ topNDocuments?: number; /** Whether queries should be restricted to use of indexed data. */ @@ -814,6 +1003,20 @@ export interface AzureMachineLearningIndexChatExtensionParameters { filter?: string; } +/** + * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + * extension. + */ +export interface AzureCosmosDBChatExtensionConfiguration extends AzureChatExtensionConfiguration { + /** + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Azure Cosmos DB. + */ + type: "AzureCosmosDB"; + /** The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. */ + parameters: AzureCosmosDBChatExtensionParameters; +} + /** * Parameters to use when configuring Azure OpenAI On Your Data chat extensions when using Azure Cosmos DB for * MongoDB vCore. @@ -826,7 +1029,7 @@ export interface AzureCosmosDBChatExtensionParameters { * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) * authentication. */ - authentication?: OnYourDataAuthenticationOptions; + authentication?: OnYourDataAuthenticationOptionsUnion; /** The configured top number of documents to feature for the configured query. */ topNDocuments?: number; /** Whether queries should be restricted to use of indexed data. */ @@ -844,7 +1047,7 @@ export interface AzureCosmosDBChatExtensionParameters { /** Customized field mapping behavior to use when interacting with the search index. */ fieldsMapping: AzureCosmosDBFieldMappingOptions; /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + embeddingDependency?: OnYourDataVectorizationSourceUnion; } /** Optional settings to control how fields are processed when using a configured Azure Cosmos DB resource. */ @@ -853,6 +1056,20 @@ export interface AzureCosmosDBFieldMappingOptions { vectorFields: string[]; } +/** + * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + * extension. + */ +export interface ElasticsearchChatExtensionConfiguration extends AzureChatExtensionConfiguration { + /** + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Elasticsearch®. + */ + type: "Elasticsearch"; + /** The parameters to use when configuring Elasticsearch®. */ + parameters: ElasticsearchChatExtensionParameters; +} + /** Parameters to use when configuring Elasticsearch® as an Azure OpenAI chat extension. */ export interface ElasticsearchChatExtensionParameters { /** @@ -862,7 +1079,7 @@ export interface ElasticsearchChatExtensionParameters { * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) * authentication. */ - authentication?: OnYourDataAuthenticationOptions; + authentication?: OnYourDataAuthenticationOptionsUnion; /** The configured top number of documents to feature for the configured query. */ topNDocuments?: number; /** Whether queries should be restricted to use of indexed data. */ @@ -880,7 +1097,7 @@ export interface ElasticsearchChatExtensionParameters { /** The query type of Elasticsearch®. */ queryType?: ElasticsearchQueryType; /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + embeddingDependency?: OnYourDataVectorizationSourceUnion; } /** Optional settings to control how fields are processed when using a configured Elasticsearch® resource. */ @@ -903,6 +1120,20 @@ export interface ElasticsearchIndexFieldMappingOptions { /** "simple", "vector" */ export type ElasticsearchQueryType = string; +/** + * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + * extension. + */ +export interface PineconeChatExtensionConfiguration extends AzureChatExtensionConfiguration { + /** + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Pinecone. + */ + type: "Pinecone"; + /** The parameters to use when configuring Azure OpenAI chat extensions. */ + parameters: PineconeChatExtensionParameters; +} + /** Parameters for configuring Azure OpenAI Pinecone chat extensions. */ export interface PineconeChatExtensionParameters { /** @@ -912,7 +1143,7 @@ export interface PineconeChatExtensionParameters { * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) * authentication. */ - authentication?: OnYourDataAuthenticationOptions; + authentication?: OnYourDataAuthenticationOptionsUnion; /** The configured top number of documents to feature for the configured query. */ topNDocuments?: number; /** Whether queries should be restricted to use of indexed data. */ @@ -928,7 +1159,7 @@ export interface PineconeChatExtensionParameters { /** Customized field mapping behavior to use when interacting with the search index. */ fieldsMapping: PineconeFieldMappingOptions; /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + embeddingDependency?: OnYourDataVectorizationSourceUnion; } /** Optional settings to control how fields are processed when using a configured Pinecone resource. */ @@ -949,6 +1180,14 @@ export interface PineconeFieldMappingOptions { imageVectorFields?: string[]; } +/** + * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat + * completions request that should use Azure OpenAI chat extensions to augment the response behavior. + * The use of this configuration is compatible only with Azure OpenAI. + */ +/** "AzureCognitiveSearch", "AzureMLIndex", "AzureCosmosDB", "Elasticsearch", "Pinecone" */ +export type AzureChatExtensionType = string; + /** A representation of the available Azure OpenAI enhancement configurations. */ export interface AzureChatEnhancementConfiguration { /** A representation of the available options for the Azure OpenAI grounding enhancement. */ @@ -969,26 +1208,63 @@ export interface AzureChatOCREnhancementConfiguration { enabled: boolean; } -/** The valid response formats Chat Completions can provide. Used to enable JSON mode. */ -/** "text", "json_object" */ -export type ChatCompletionsResponseFormat = string; +/** + * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + * mode. + */ +export interface ChatCompletionsResponseFormat { + /** the discriminator possible values: text, json_object */ + type: string; +} + +/** + * The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response + * content that adheres to a specific schema. + */ +export interface ChatCompletionsTextResponseFormat extends ChatCompletionsResponseFormat { + /** The discriminated object type, which is always 'text' for this format. */ + type: "text"; +} + +/** A response format for Chat Completions that restricts responses to emitting valid JSON objects. */ +export interface ChatCompletionsJsonResponseFormat extends ChatCompletionsResponseFormat { + /** The discriminated object type, which is always 'json_object' for this format. */ + type: "json_object"; +} /** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ export interface ChatCompletionsToolDefinition { - /** the discriminator possible values function */ + /** the discriminator possible values: function */ type: string; } +/** The definition information for a chat completions function tool that can call a function in response to a tool call. */ +export interface ChatCompletionsFunctionToolDefinition extends ChatCompletionsToolDefinition { + /** The object name, which is always 'function'. */ + type: "function"; + /** The function definition details for the function tool. */ + function: FunctionDefinition; +} + /** Represents a generic policy for how a chat completions tool may be selected. */ /** "auto", "none" */ export type ChatCompletionsToolSelectionPreset = string; /** An abstract representation of an explicit, named tool selection to use for a chat completions request. */ export interface ChatCompletionsNamedToolSelection { - /** the discriminator possible values function */ + /** the discriminator possible values: function */ type: string; } +/** A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ +export interface ChatCompletionsNamedFunctionToolSelection + extends ChatCompletionsNamedToolSelection { + /** The object type, which is always 'function'. */ + type: "function"; + /** The name of the function that should be called. */ + name: string; +} + /** * Representation of the response data from a chat completions request. * Completions support a wide variety of tasks and generate text that continues from or "completes" @@ -1017,7 +1293,7 @@ export interface ChatCompletions { * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that * might impact determinism. */ - systemFingerprint: string; + systemFingerprint?: string; /** Usage information for tokens processed and generated as part of this completions operation. */ usage: CompletionsUsage; } @@ -1038,7 +1314,7 @@ export interface ChatChoice { * The reason the model stopped generating tokens, together with any applicable details. * This structured representation replaces 'finish_reason' for some models. */ - finishDetails?: ChatFinishDetails; + finishDetails?: ChatFinishDetailsUnion; /** The delta message content for a streaming response. */ delta?: ChatResponseMessage; /** @@ -1065,7 +1341,7 @@ export interface ChatResponseMessage { * The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat * completions request to resolve as configured. */ - toolCalls?: ChatCompletionsToolCall[]; + toolCalls?: ChatCompletionsToolCallUnion[]; /** * The function call that must be resolved and have its output appended to subsequent input messages for the chat * completions request to resolve as configured. @@ -1095,10 +1371,27 @@ export interface AzureChatExtensionsMessageContext { /** An abstract representation of structured information about why a chat completions response terminated. */ export interface ChatFinishDetails { - /** the discriminator possible values stop, max_tokens */ + /** the discriminator possible values: stop, max_tokens */ type: string; } +/** A structured representation of a stop reason that signifies natural termination by the model. */ +export interface StopFinishDetails extends ChatFinishDetails { + /** The object type, which is always 'stop' for this object. */ + type: "stop"; + /** The token sequence that the model terminated with. */ + stop: string; +} + +/** + * A structured representation of a stop reason that signifies a token limit was reached before the model could naturally + * complete. + */ +export interface MaxTokensFinishDetails extends ChatFinishDetails { + /** The object type, which is always 'max_tokens' for this object. */ + type: "max_tokens"; +} + /** * Represents the output results of Azure enhancements to chat completions, as configured via the matching input provided * in the request. @@ -1285,3 +1578,58 @@ export interface EmbeddingsUsage { /** Total number of tokens transacted in this request/response. */ totalTokens: number; } + +/** Alias for ChatRequestMessageUnion */ +export type ChatRequestMessageUnion = + | ChatRequestSystemMessage + | ChatRequestUserMessage + | ChatRequestAssistantMessage + | ChatRequestToolMessage + | ChatRequestFunctionMessage + | ChatRequestMessage; +/** Alias for ChatMessageContentItemUnion */ +export type ChatMessageContentItemUnion = + | ChatMessageTextContentItem + | ChatMessageImageContentItem + | ChatMessageContentItem; +/** Alias for ChatCompletionsToolCallUnion */ +export type ChatCompletionsToolCallUnion = + | ChatCompletionsFunctionToolCall + | ChatCompletionsToolCall; +/** Alias for AzureChatExtensionConfigurationUnion */ +export type AzureChatExtensionConfigurationUnion = + | AzureCognitiveSearchChatExtensionConfiguration + | AzureMachineLearningIndexChatExtensionConfiguration + | AzureCosmosDBChatExtensionConfiguration + | ElasticsearchChatExtensionConfiguration + | PineconeChatExtensionConfiguration + | AzureChatExtensionConfiguration; +/** Alias for OnYourDataAuthenticationOptionsUnion */ +export type OnYourDataAuthenticationOptionsUnion = + | OnYourDataApiKeyAuthenticationOptions + | OnYourDataConnectionStringAuthenticationOptions + | OnYourDataKeyAndKeyIdAuthenticationOptions + | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions + | OnYourDataUserAssignedManagedIdentityAuthenticationOptions + | OnYourDataAuthenticationOptions; +/** Alias for OnYourDataVectorizationSourceUnion */ +export type OnYourDataVectorizationSourceUnion = + | OnYourDataEndpointVectorizationSource + | OnYourDataDeploymentNameVectorizationSource + | OnYourDataModelIdVectorizationSource + | OnYourDataVectorizationSource; +/** Alias for ChatCompletionsResponseFormatUnion */ +export type ChatCompletionsResponseFormatUnion = + | ChatCompletionsTextResponseFormat + | ChatCompletionsJsonResponseFormat + | ChatCompletionsResponseFormat; +/** Alias for ChatCompletionsToolDefinitionUnion */ +export type ChatCompletionsToolDefinitionUnion = + | ChatCompletionsFunctionToolDefinition + | ChatCompletionsToolDefinition; +/** Alias for ChatCompletionsNamedToolSelectionUnion */ +export type ChatCompletionsNamedToolSelectionUnion = + | ChatCompletionsNamedFunctionToolSelection + | ChatCompletionsNamedToolSelection; +/** Alias for ChatFinishDetailsUnion */ +export type ChatFinishDetailsUnion = StopFinishDetails | MaxTokensFinishDetails | ChatFinishDetails; diff --git a/sdk/openai/openai/generated/models/options.ts b/sdk/openai/openai/generated/models/options.ts new file mode 100644 index 000000000000..9151f8606d01 --- /dev/null +++ b/sdk/openai/openai/generated/models/options.ts @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { OperationOptions } from "@azure-rest/core-client"; + +export interface GetAudioTranscriptionAsPlainTextOptions extends OperationOptions {} + +export interface GetAudioTranscriptionAsResponseObjectOptions extends OperationOptions { + /** The content type for the operation. Always multipart/form-data for this operation. */ + contentType?: string; +} + +export interface GetAudioTranslationAsPlainTextOptions extends OperationOptions {} + +export interface GetAudioTranslationAsResponseObjectOptions extends OperationOptions { + /** The content type for the operation. Always multipart/form-data for this operation. */ + contentType?: string; +} + +export interface GetCompletionsOptions extends OperationOptions {} + +export interface GetChatCompletionsOptions extends OperationOptions {} + +export interface GetChatCompletionsWithAzureExtensionsOptions extends OperationOptions {} + +export interface GetImageGenerationsOptions extends OperationOptions {} + +export interface GetEmbeddingsOptions extends OperationOptions {} diff --git a/sdk/openai/openai/sources/generated/src/rest/clientDefinitions.ts b/sdk/openai/openai/generated/rest/clientDefinitions.ts similarity index 79% rename from sdk/openai/openai/sources/generated/src/rest/clientDefinitions.ts rename to sdk/openai/openai/generated/rest/clientDefinitions.ts index d172d5daa34d..e9974f529a09 100644 --- a/sdk/openai/openai/sources/generated/src/rest/clientDefinitions.ts +++ b/sdk/openai/openai/generated/rest/clientDefinitions.ts @@ -46,17 +46,16 @@ export interface GetAudioTranscriptionAsPlainText { * written language corresponding to the language it was spoken in. */ post( - options?: GetAudioTranscriptionAsPlainTextParameters + options?: GetAudioTranscriptionAsPlainTextParameters, ): StreamableMethod< - | GetAudioTranscriptionAsPlainText200Response - | GetAudioTranscriptionAsPlainTextDefaultResponse + GetAudioTranscriptionAsPlainText200Response | GetAudioTranscriptionAsPlainTextDefaultResponse >; /** * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the * written language corresponding to the language it was spoken in. */ post( - options: GetAudioTranscriptionAsResponseObjectParameters + options: GetAudioTranscriptionAsResponseObjectParameters, ): StreamableMethod< | GetAudioTranscriptionAsResponseObject200Response | GetAudioTranscriptionAsResponseObjectDefaultResponse @@ -66,14 +65,13 @@ export interface GetAudioTranscriptionAsPlainText { export interface GetAudioTranslationAsPlainText { /** Gets English language transcribed text and associated metadata from provided spoken audio data. */ post( - options?: GetAudioTranslationAsPlainTextParameters + options?: GetAudioTranslationAsPlainTextParameters, ): StreamableMethod< - | GetAudioTranslationAsPlainText200Response - | GetAudioTranslationAsPlainTextDefaultResponse + GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsPlainTextDefaultResponse >; /** Gets English language transcribed text and associated metadata from provided spoken audio data. */ post( - options: GetAudioTranslationAsResponseObjectParameters + options: GetAudioTranslationAsResponseObjectParameters, ): StreamableMethod< | GetAudioTranslationAsResponseObject200Response | GetAudioTranslationAsResponseObjectDefaultResponse @@ -87,10 +85,8 @@ export interface GetCompletions { * provided prompt data. */ post( - options?: GetCompletionsParameters - ): StreamableMethod< - GetCompletions200Response | GetCompletionsDefaultResponse - >; + options?: GetCompletionsParameters, + ): StreamableMethod; } export interface GetChatCompletions { @@ -100,10 +96,8 @@ export interface GetChatCompletions { * provided prompt data. */ post( - options?: GetChatCompletionsParameters - ): StreamableMethod< - GetChatCompletions200Response | GetChatCompletionsDefaultResponse - >; + options?: GetChatCompletionsParameters, + ): StreamableMethod; } export interface GetChatCompletionsWithAzureExtensions { @@ -113,7 +107,7 @@ export interface GetChatCompletionsWithAzureExtensions { * other augmentations to the base chat completions capabilities. */ post( - options?: GetChatCompletionsWithAzureExtensionsParameters + options?: GetChatCompletionsWithAzureExtensionsParameters, ): StreamableMethod< | GetChatCompletionsWithAzureExtensions200Response | GetChatCompletionsWithAzureExtensionsDefaultResponse @@ -123,23 +117,21 @@ export interface GetChatCompletionsWithAzureExtensions { export interface GetImageGenerations { /** Creates an image given a prompt. */ post( - options?: GetImageGenerationsParameters - ): StreamableMethod< - GetImageGenerations200Response | GetImageGenerationsDefaultResponse - >; + options?: GetImageGenerationsParameters, + ): StreamableMethod; } export interface GetEmbeddings { /** Return the embeddings for a given prompt. */ post( - options?: GetEmbeddingsParameters + options?: GetEmbeddingsParameters, ): StreamableMethod; } export interface GetAzureBatchImageGenerationOperationStatus { /** Returns the status of the images operation */ get( - options?: GetAzureBatchImageGenerationOperationStatusParameters + options?: GetAzureBatchImageGenerationOperationStatusParameters, ): StreamableMethod< | GetAzureBatchImageGenerationOperationStatus200Response | GetAzureBatchImageGenerationOperationStatusDefaultResponse @@ -149,10 +141,9 @@ export interface GetAzureBatchImageGenerationOperationStatus { export interface BeginAzureBatchImageGeneration { /** Starts the generation of a batch of images from a text caption */ post( - options?: BeginAzureBatchImageGenerationParameters + options?: BeginAzureBatchImageGenerationParameters, ): StreamableMethod< - | BeginAzureBatchImageGeneration202Response - | BeginAzureBatchImageGenerationDefaultResponse + BeginAzureBatchImageGeneration202Response | BeginAzureBatchImageGenerationDefaultResponse >; } @@ -160,42 +151,33 @@ export interface Routes { /** Resource for '/deployments/\{deploymentId\}/audio/transcriptions' has methods for the following verbs: post */ ( path: "/deployments/{deploymentId}/audio/transcriptions", - deploymentId: string + deploymentId: string, ): GetAudioTranscriptionAsPlainText; /** Resource for '/deployments/\{deploymentId\}/audio/translations' has methods for the following verbs: post */ ( path: "/deployments/{deploymentId}/audio/translations", - deploymentId: string + deploymentId: string, ): GetAudioTranslationAsPlainText; /** Resource for '/deployments/\{deploymentId\}/completions' has methods for the following verbs: post */ - ( - path: "/deployments/{deploymentId}/completions", - deploymentId: string - ): GetCompletions; + (path: "/deployments/{deploymentId}/completions", deploymentId: string): GetCompletions; /** Resource for '/deployments/\{deploymentId\}/chat/completions' has methods for the following verbs: post */ - ( - path: "/deployments/{deploymentId}/chat/completions", - deploymentId: string - ): GetChatCompletions; + (path: "/deployments/{deploymentId}/chat/completions", deploymentId: string): GetChatCompletions; /** Resource for '/deployments/\{deploymentId\}/extensions/chat/completions' has methods for the following verbs: post */ ( path: "/deployments/{deploymentId}/extensions/chat/completions", - deploymentId: string + deploymentId: string, ): GetChatCompletionsWithAzureExtensions; /** Resource for '/deployments/\{deploymentId\}/images/generations' has methods for the following verbs: post */ ( path: "/deployments/{deploymentId}/images/generations", - deploymentId: string + deploymentId: string, ): GetImageGenerations; /** Resource for '/deployments/\{deploymentId\}/embeddings' has methods for the following verbs: post */ - ( - path: "/deployments/{deploymentId}/embeddings", - deploymentId: string - ): GetEmbeddings; + (path: "/deployments/{deploymentId}/embeddings", deploymentId: string): GetEmbeddings; /** Resource for '/operations/images/\{operationId\}' has methods for the following verbs: get */ ( path: "/operations/images/{operationId}", - operationId: string + operationId: string, ): GetAzureBatchImageGenerationOperationStatus; /** Resource for '/images/generations:submit' has methods for the following verbs: post */ (path: "/images/generations:submit"): BeginAzureBatchImageGeneration; diff --git a/sdk/openai/openai/sources/generated/src/rest/index.ts b/sdk/openai/openai/generated/rest/index.ts similarity index 68% rename from sdk/openai/openai/sources/generated/src/rest/index.ts rename to sdk/openai/openai/generated/rest/index.ts index a2d1968f9077..938c70667fee 100644 --- a/sdk/openai/openai/sources/generated/src/rest/index.ts +++ b/sdk/openai/openai/generated/rest/index.ts @@ -10,5 +10,12 @@ export * from "./clientDefinitions.js"; export * from "./isUnexpected.js"; export * from "./models.js"; export * from "./outputModels.js"; +export * from "./pollingHelper.js"; +export { + createFile, + createFileFromStream, + type CreateFileOptions, + type CreateFileFromStreamOptions, +} from "@azure/core-rest-pipeline"; export default OpenAIClient; diff --git a/sdk/openai/openai/sources/generated/src/rest/isUnexpected.ts b/sdk/openai/openai/generated/rest/isUnexpected.ts similarity index 91% rename from sdk/openai/openai/sources/generated/src/rest/isUnexpected.ts rename to sdk/openai/openai/generated/rest/isUnexpected.ts index 50fb5207448b..f9ad3ca93c31 100644 --- a/sdk/openai/openai/sources/generated/src/rest/isUnexpected.ts +++ b/sdk/openai/openai/generated/rest/isUnexpected.ts @@ -42,41 +42,41 @@ export function isUnexpected( response: | GetAudioTranscriptionAsPlainText200Response | GetAudioTranscriptionAsResponseObject200Response - | GetAudioTranscriptionAsPlainTextDefaultResponse + | GetAudioTranscriptionAsPlainTextDefaultResponse, ): response is GetAudioTranscriptionAsPlainTextDefaultResponse; export function isUnexpected( response: | GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsResponseObject200Response - | GetAudioTranslationAsPlainTextDefaultResponse + | GetAudioTranslationAsPlainTextDefaultResponse, ): response is GetAudioTranslationAsPlainTextDefaultResponse; export function isUnexpected( - response: GetCompletions200Response | GetCompletionsDefaultResponse + response: GetCompletions200Response | GetCompletionsDefaultResponse, ): response is GetCompletionsDefaultResponse; export function isUnexpected( - response: GetChatCompletions200Response | GetChatCompletionsDefaultResponse + response: GetChatCompletions200Response | GetChatCompletionsDefaultResponse, ): response is GetChatCompletionsDefaultResponse; export function isUnexpected( response: | GetChatCompletionsWithAzureExtensions200Response - | GetChatCompletionsWithAzureExtensionsDefaultResponse + | GetChatCompletionsWithAzureExtensionsDefaultResponse, ): response is GetChatCompletionsWithAzureExtensionsDefaultResponse; export function isUnexpected( - response: GetImageGenerations200Response | GetImageGenerationsDefaultResponse + response: GetImageGenerations200Response | GetImageGenerationsDefaultResponse, ): response is GetImageGenerationsDefaultResponse; export function isUnexpected( - response: GetEmbeddings200Response | GetEmbeddingsDefaultResponse + response: GetEmbeddings200Response | GetEmbeddingsDefaultResponse, ): response is GetEmbeddingsDefaultResponse; export function isUnexpected( response: | GetAzureBatchImageGenerationOperationStatus200Response - | GetAzureBatchImageGenerationOperationStatusDefaultResponse + | GetAzureBatchImageGenerationOperationStatusDefaultResponse, ): response is GetAzureBatchImageGenerationOperationStatusDefaultResponse; export function isUnexpected( response: | BeginAzureBatchImageGeneration202Response | BeginAzureBatchImageGenerationLogicalResponse - | BeginAzureBatchImageGenerationDefaultResponse + | BeginAzureBatchImageGenerationDefaultResponse, ): response is BeginAzureBatchImageGenerationDefaultResponse; export function isUnexpected( response: @@ -100,7 +100,7 @@ export function isUnexpected( | GetAzureBatchImageGenerationOperationStatusDefaultResponse | BeginAzureBatchImageGeneration202Response | BeginAzureBatchImageGenerationLogicalResponse - | BeginAzureBatchImageGenerationDefaultResponse + | BeginAzureBatchImageGenerationDefaultResponse, ): response is | GetAudioTranscriptionAsPlainTextDefaultResponse | GetAudioTranslationAsPlainTextDefaultResponse @@ -143,24 +143,17 @@ function getParametrizedPathSuccess(method: string, path: string): string[] { // track if we have found a match to return the values found. let found = true; - for ( - let i = candidateParts.length - 1, j = pathParts.length - 1; - i >= 1 && j >= 1; - i--, j-- - ) { - if ( - candidateParts[i]?.startsWith("{") && - candidateParts[i]?.indexOf("}") !== -1 - ) { + for (let i = candidateParts.length - 1, j = pathParts.length - 1; i >= 1 && j >= 1; i--, j--) { + if (candidateParts[i]?.startsWith("{") && candidateParts[i]?.indexOf("}") !== -1) { const start = candidateParts[i]!.indexOf("}") + 1, end = candidateParts[i]?.length; // If the current part of the candidate is a "template" part // Try to use the suffix of pattern to match the path // {guid} ==> $ // {guid}:export ==> :export$ - const isMatched = new RegExp( - `${candidateParts[i]?.slice(start, end)}` - ).test(pathParts[j] || ""); + const isMatched = new RegExp(`${candidateParts[i]?.slice(start, end)}`).test( + pathParts[j] || "", + ); if (!isMatched) { found = false; diff --git a/sdk/openai/openai/sources/generated/src/rest/models.ts b/sdk/openai/openai/generated/rest/models.ts similarity index 92% rename from sdk/openai/openai/sources/generated/src/rest/models.ts rename to sdk/openai/openai/generated/rest/models.ts index 8f6f258371a1..4aa90504d4fc 100644 --- a/sdk/openai/openai/sources/generated/src/rest/models.ts +++ b/sdk/openai/openai/generated/rest/models.ts @@ -6,14 +6,17 @@ export interface AudioTranscriptionOptions { /** * The audio data to transcribe. This must be the binary content of a file in one of the supported media formats: * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + * + * NOTE: The following type 'File' is part of WebAPI and available since Node 20. If your Node version is lower than Node 20. + * You could leverage our helpers 'createFile' or 'createFileFromStream' to create a File object. They could help you specify filename, type, and others. */ - file: string; + file: string | Uint8Array | ReadableStream | NodeJS.ReadableStream | File; /** The optional filename or descriptive identifier to associate with with the audio data. */ filename?: string; /** * The requested format of the transcription response data, which will influence the content and detail of the result. * - * Possible values: json, verbose_json, text, srt, vtt + * Possible values: "json", "verbose_json", "text", "srt", "vtt" */ response_format?: string; /** @@ -42,14 +45,17 @@ export interface AudioTranslationOptions { /** * The audio data to translate. This must be the binary content of a file in one of the supported media formats: * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm. + * + * NOTE: The following type 'File' is part of WebAPI and available since Node 20. If your Node version is lower than Node 20. + * You could leverage our helpers 'createFile' or 'createFileFromStream' to create a File object. They could help you specify filename, type, and others. */ - file: string; + file: string | Uint8Array | ReadableStream | NodeJS.ReadableStream | File; /** The optional filename or descriptive identifier to associate with with the audio data. */ filename?: string; /** * The requested format of the translation response data, which will influence the content and detail of the result. * - * Possible values: json, verbose_json, text, srt, vtt + * Possible values: "json", "verbose_json", "text", "srt", "vtt" */ response_format?: string; /** @@ -257,12 +263,8 @@ export interface ChatCompletionsOptions { * system_fingerprint response parameter to monitor changes in the backend." */ seed?: number; - /** - * An object specifying the format that the model must output. Used to enable JSON mode. - * - * Possible values: text, json_object - */ - response_format?: string; + /** An object specifying the format that the model must output. Used to enable JSON mode. */ + response_format?: ChatCompletionsResponseFormat; /** The available tool definitions that the chat completions request can use, including caller-defined functions. */ tools?: Array; /** If specified, the model will configure which of the provided tools it can use for the chat completions response. */ @@ -303,8 +305,7 @@ export interface ChatMessageContentItemParent { } /** A structured chat content item containing plain text. */ -export interface ChatMessageTextContentItem - extends ChatMessageContentItemParent { +export interface ChatMessageTextContentItem extends ChatMessageContentItemParent { /** The discriminated object type: always 'text' for this type. */ type: "text"; /** The content of the message. */ @@ -312,25 +313,24 @@ export interface ChatMessageTextContentItem } /** A structured chat content item containing an image reference. */ -export interface ChatMessageImageContentItem - extends ChatMessageContentItemParent { +export interface ChatMessageImageContentItem extends ChatMessageContentItemParent { /** The discriminated object type: always 'image_url' for this type. */ type: "image_url"; /** An internet location, which must be accessible to the model,from which the image may be retrieved. */ image_url: ChatMessageImageUrl; - /** - * The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and - * accuracy. - * - * Possible values: auto, low, high - */ - detail?: string; } /** An internet location from which the model may retrieve an image. */ export interface ChatMessageImageUrl { /** The URL of the image. */ url: string; + /** + * The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and + * accuracy. + * + * Possible values: "auto", "low", "high" + */ + detail?: string; } /** A request chat message representing response or action from the assistant. */ @@ -367,8 +367,7 @@ export interface ChatCompletionsToolCallParent { * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents * a function invocation needed for a subsequent chat completions request to resolve. */ -export interface ChatCompletionsFunctionToolCall - extends ChatCompletionsToolCallParent { +export interface ChatCompletionsFunctionToolCall extends ChatCompletionsToolCallParent { /** The type of tool call, in this case always 'function'. */ type: "function"; /** The details of the function invocation requested by the tool call. */ @@ -483,7 +482,7 @@ export interface AzureCognitiveSearchChatExtensionParameters { /** * The query type to use with Azure Cognitive Search. * - * Possible values: simple, semantic, vector, vectorSimpleHybrid, vectorSemanticHybrid + * Possible values: "simple", "semantic", "vector", "vectorSimpleHybrid", "vectorSemanticHybrid" */ queryType?: string; /** The additional semantic configuration for the query. */ @@ -575,8 +574,7 @@ export interface OnYourDataVectorizationSourceParent { * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on a public Azure OpenAI endpoint call for embeddings. */ -export interface OnYourDataEndpointVectorizationSource - extends OnYourDataVectorizationSourceParent { +export interface OnYourDataEndpointVectorizationSource extends OnYourDataVectorizationSourceParent { /** The type of vectorization source to use. Always 'Endpoint' for this type. */ type: "Endpoint"; /** Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. */ @@ -601,8 +599,7 @@ export interface OnYourDataDeploymentNameVectorizationSource * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based * on a search service model ID. Currently only supported by Elasticsearch®. */ -export interface OnYourDataModelIdVectorizationSource - extends OnYourDataVectorizationSourceParent { +export interface OnYourDataModelIdVectorizationSource extends OnYourDataVectorizationSourceParent { /** The type of vectorization source to use. Always 'ModelId' for this type. */ type: "ModelId"; /** The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. */ @@ -748,7 +745,7 @@ export interface ElasticsearchChatExtensionParameters { /** * The query type of Elasticsearch®. * - * Possible values: simple, vector + * Possible values: "simple", "vector" */ queryType?: string; /** The embedding dependency for vector search. */ @@ -775,8 +772,7 @@ export interface ElasticsearchIndexFieldMappingOptions { * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat * extension. */ -export interface PineconeChatExtensionConfiguration - extends AzureChatExtensionConfigurationParent { +export interface PineconeChatExtensionConfiguration extends AzureChatExtensionConfigurationParent { /** * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its * default value for Pinecone. @@ -852,14 +848,36 @@ export interface AzureChatOCREnhancementConfiguration { enabled: boolean; } +/** + * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + * mode. + */ +export interface ChatCompletionsResponseFormatParent { + type: string; +} + +/** + * The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response + * content that adheres to a specific schema. + */ +export interface ChatCompletionsTextResponseFormat extends ChatCompletionsResponseFormatParent { + /** The discriminated object type, which is always 'text' for this format. */ + type: "text"; +} + +/** A response format for Chat Completions that restricts responses to emitting valid JSON objects. */ +export interface ChatCompletionsJsonResponseFormat extends ChatCompletionsResponseFormatParent { + /** The discriminated object type, which is always 'json_object' for this format. */ + type: "json_object"; +} + /** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ export interface ChatCompletionsToolDefinitionParent { type: string; } /** The definition information for a chat completions function tool that can call a function in response to a tool call. */ -export interface ChatCompletionsFunctionToolDefinition - extends ChatCompletionsToolDefinitionParent { +export interface ChatCompletionsFunctionToolDefinition extends ChatCompletionsToolDefinitionParent { /** The object name, which is always 'function'. */ type: "function"; /** The function definition details for the function tool. */ @@ -877,7 +895,7 @@ export interface ChatCompletionsNamedFunctionToolSelection /** The object type, which is always 'function'. */ type: "function"; /** The name of the function that should be called. */ - name: "string"; + name: string; } /** Represents the request data used to generate images. */ @@ -900,27 +918,27 @@ export interface ImageGenerationOptions { * Dall-e-2 models support 256x256, 512x512, or 1024x1024. * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. * - * Possible values: 256x256, 512x512, 1024x1024, 1792x1024, 1024x1792 + * Possible values: "256x256", "512x512", "1024x1024", "1792x1024", "1024x1792" */ size?: string; /** * The format in which image generation response items should be presented. * - * Possible values: url, b64_json + * Possible values: "url", "b64_json" */ response_format?: string; /** * The desired image generation quality level to use. * Only configurable with dall-e-3 models. * - * Possible values: standard, hd + * Possible values: "standard", "hd" */ quality?: string; /** * The desired image generation style to use. * Only configurable with dall-e-3 models. * - * Possible values: natural, vivid + * Possible values: "natural", "vivid" */ style?: string; /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ @@ -956,6 +974,7 @@ export interface EmbeddingsOptions { /** An abstract representation of a chat message as provided in a request. */ export type ChatRequestMessage = + | ChatRequestMessageParent | ChatRequestSystemMessage | ChatRequestUserMessage | ChatRequestAssistantMessage @@ -963,19 +982,23 @@ export type ChatRequestMessage = | ChatRequestFunctionMessage; /** An abstract representation of a structured content item within a chat message. */ export type ChatMessageContentItem = + | ChatMessageContentItemParent | ChatMessageTextContentItem | ChatMessageImageContentItem; /** * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested * chat completion. */ -export type ChatCompletionsToolCall = ChatCompletionsFunctionToolCall; +export type ChatCompletionsToolCall = + | ChatCompletionsToolCallParent + | ChatCompletionsFunctionToolCall; /** * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat * completions request that should use Azure OpenAI chat extensions to augment the response behavior. * The use of this configuration is compatible only with Azure OpenAI. */ export type AzureChatExtensionConfiguration = + | AzureChatExtensionConfigurationParent | AzureCognitiveSearchChatExtensionConfiguration | AzureMachineLearningIndexChatExtensionConfiguration | AzureCosmosDBChatExtensionConfiguration @@ -983,6 +1006,7 @@ export type AzureChatExtensionConfiguration = | PineconeChatExtensionConfiguration; /** The authentication options for Azure OpenAI On Your Data. */ export type OnYourDataAuthenticationOptions = + | OnYourDataAuthenticationOptionsParent | OnYourDataApiKeyAuthenticationOptions | OnYourDataConnectionStringAuthenticationOptions | OnYourDataKeyAndKeyIdAuthenticationOptions @@ -990,12 +1014,23 @@ export type OnYourDataAuthenticationOptions = | OnYourDataUserAssignedManagedIdentityAuthenticationOptions; /** An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ export type OnYourDataVectorizationSource = + | OnYourDataVectorizationSourceParent | OnYourDataEndpointVectorizationSource | OnYourDataDeploymentNameVectorizationSource | OnYourDataModelIdVectorizationSource; +/** + * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + * mode. + */ +export type ChatCompletionsResponseFormat = + | ChatCompletionsResponseFormatParent + | ChatCompletionsTextResponseFormat + | ChatCompletionsJsonResponseFormat; /** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ export type ChatCompletionsToolDefinition = - ChatCompletionsFunctionToolDefinition; + | ChatCompletionsToolDefinitionParent + | ChatCompletionsFunctionToolDefinition; /** An abstract representation of an explicit, named tool selection to use for a chat completions request. */ export type ChatCompletionsNamedToolSelection = - ChatCompletionsNamedFunctionToolSelection; + | ChatCompletionsNamedToolSelectionParent + | ChatCompletionsNamedFunctionToolSelection; diff --git a/sdk/openai/openai/sources/generated/src/rest/openAIClient.ts b/sdk/openai/openai/generated/rest/openAIClient.ts similarity index 91% rename from sdk/openai/openai/sources/generated/src/rest/openAIClient.ts rename to sdk/openai/openai/generated/rest/openAIClient.ts index d21d64e5ed4e..04d76a8d2f47 100644 --- a/sdk/openai/openai/sources/generated/src/rest/openAIClient.ts +++ b/sdk/openai/openai/generated/rest/openAIClient.ts @@ -16,7 +16,7 @@ import { OpenAIContext } from "./clientDefinitions.js"; export default function createClient( endpoint: string, credentials: TokenCredential | KeyCredential, - options: ClientOptions = {} + options: ClientOptions = {}, ): OpenAIContext { const baseUrl = options.baseUrl ?? `${endpoint}/openai`; options.apiVersion = options.apiVersion ?? "2023-12-01-preview"; @@ -34,9 +34,7 @@ export default function createClient( logger: options.loggingOptions?.logger ?? logger.info, }, credentials: { - scopes: options.credentials?.scopes ?? [ - "https://cognitiveservices.azure.com/.default", - ], + scopes: options.credentials?.scopes ?? ["https://cognitiveservices.azure.com/.default"], apiKeyHeaderName: options.credentials?.apiKeyHeaderName ?? "api-key", }, }; diff --git a/sdk/openai/openai/sources/generated/src/rest/outputModels.ts b/sdk/openai/openai/generated/rest/outputModels.ts similarity index 96% rename from sdk/openai/openai/sources/generated/src/rest/outputModels.ts rename to sdk/openai/openai/generated/rest/outputModels.ts index 5886d1948871..c7d09af7c6e3 100644 --- a/sdk/openai/openai/sources/generated/src/rest/outputModels.ts +++ b/sdk/openai/openai/generated/rest/outputModels.ts @@ -16,7 +16,7 @@ export interface AudioTranscriptionOutput { /** * The label that describes which operation type generated the accompanying response data. * - * Possible values: transcribe, translate + * Possible values: "transcribe", "translate" */ task?: string; /** @@ -71,7 +71,7 @@ export interface AudioTranslationOutput { /** * The label that describes which operation type generated the accompanying response data. * - * Possible values: transcribe, translate + * Possible values: "transcribe", "translate" */ task?: string; /** @@ -136,7 +136,7 @@ export interface CompletionsOutput { * Content filtering results for zero or more prompts in the request. In a streaming request, * results for different prompts may arrive at different times or in different orders. */ - prompt_filter_results: Array; + prompt_filter_results?: Array; /** * The collection of completions choices associated with this completions response. * Generally, `n` choices are generated per provided prompt with a default value of 1. @@ -152,7 +152,7 @@ export interface ContentFilterResultsForPromptOutput { /** The index of this prompt in the set of prompt results */ prompt_index: number; /** Content filtering results for this prompt */ - content_filter_results?: ContentFilterResultDetailsForPromptOutput; + content_filter_results: ContentFilterResultDetailsForPromptOutput; } /** Information about content filtering evaluated against input data to Azure OpenAI. */ @@ -200,7 +200,7 @@ export interface ContentFilterResultOutput { /** * Ratings for the intensity and risk level of filtered content. * - * Possible values: safe, low, medium, high + * Possible values: "safe", "low", "medium", "high" */ severity: string; /** A value indicating whether or not the content has been filtered. */ @@ -339,8 +339,7 @@ export interface ChatCompletionsToolCallOutputParent { * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents * a function invocation needed for a subsequent chat completions request to resolve. */ -export interface ChatCompletionsFunctionToolCallOutput - extends ChatCompletionsToolCallOutputParent { +export interface ChatCompletionsFunctionToolCallOutput extends ChatCompletionsToolCallOutputParent { /** The type of tool call, in this case always 'function'. */ type: "function"; /** The details of the function invocation requested by the tool call. */ @@ -388,7 +387,7 @@ export interface ChatCompletionsOutput { * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that * might impact determinism. */ - system_fingerprint: string; + system_fingerprint?: string; /** Usage information for tokens processed and generated as part of this completions operation. */ usage: CompletionsUsageOutput; } @@ -423,7 +422,7 @@ export interface ChatChoiceOutput { * provided in the request. This supplementary information is only available when using Azure OpenAI and only when the * request is configured to use enhancements. */ - enhancements: AzureChatEnhancementsOutput; + enhancements?: AzureChatEnhancementsOutput; } /** A representation of a chat message as received in a response. */ @@ -431,7 +430,7 @@ export interface ChatResponseMessageOutput { /** * The chat role associated with the message. * - * Possible values: system, assistant, user, function, tool + * Possible values: "system", "assistant", "user", "function", "tool" */ role: string; /** The content of the message. */ @@ -485,8 +484,7 @@ export interface StopFinishDetailsOutput extends ChatFinishDetailsOutputParent { * A structured representation of a stop reason that signifies a token limit was reached before the model could naturally * complete. */ -export interface MaxTokensFinishDetailsOutput - extends ChatFinishDetailsOutputParent { +export interface MaxTokensFinishDetailsOutput extends ChatFinishDetailsOutputParent { /** The object type, which is always 'max_tokens' for this object. */ type: "max_tokens"; } @@ -537,6 +535,53 @@ export interface AzureGroundingEnhancementCoordinatePointOutput { y: number; } +/** Represents the request data used to generate images. */ +export interface ImageGenerationOptionsOutput { + /** + * The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be + * inferred as a default. + */ + model?: string; + /** A description of the desired images. */ + prompt: string; + /** + * The number of images to generate. + * Dall-e-2 models support values between 1 and 10. + * Dall-e-3 models only support a value of 1. + */ + n?: number; + /** + * The desired dimensions for generated images. + * Dall-e-2 models support 256x256, 512x512, or 1024x1024. + * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. + * + * Possible values: "256x256", "512x512", "1024x1024", "1792x1024", "1024x1792" + */ + size?: string; + /** + * The format in which image generation response items should be presented. + * + * Possible values: "url", "b64_json" + */ + response_format?: string; + /** + * The desired image generation quality level to use. + * Only configurable with dall-e-3 models. + * + * Possible values: "standard", "hd" + */ + quality?: string; + /** + * The desired image generation style to use. + * Only configurable with dall-e-3 models. + * + * Possible values: "natural", "vivid" + */ + style?: string; + /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ + user?: string; +} + /** The result of a successful image generation operation. */ export interface ImageGenerationsOutput { /** @@ -608,67 +653,22 @@ export interface BatchImageGenerationOperationResponseOutput { /** * The status of the operation * - * Possible values: notRunning, running, succeeded, canceled, failed + * Possible values: "notRunning", "running", "succeeded", "canceled", "failed" */ status: string; /** The error if the operation failed. */ error?: ErrorModel; } -/** Represents the request data used to generate images. */ -export interface ImageGenerationOptionsOutput { - /** - * The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be - * inferred as a default. - */ - model?: string; - /** A description of the desired images. */ - prompt: string; - /** - * The number of images to generate. - * Dall-e-2 models support values between 1 and 10. - * Dall-e-3 models only support a value of 1. - */ - n?: number; - /** - * The desired dimensions for generated images. - * Dall-e-2 models support 256x256, 512x512, or 1024x1024. - * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. - * - * Possible values: 256x256, 512x512, 1024x1024, 1792x1024, 1024x1792 - */ - size?: string; - /** - * The format in which image generation response items should be presented. - * - * Possible values: url, b64_json - */ - response_format?: string; - /** - * The desired image generation quality level to use. - * Only configurable with dall-e-3 models. - * - * Possible values: standard, hd - */ - quality?: string; - /** - * The desired image generation style to use. - * Only configurable with dall-e-3 models. - * - * Possible values: natural, vivid - */ - style?: string; - /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ - user?: string; -} - /** * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested * chat completion. */ export type ChatCompletionsToolCallOutput = - ChatCompletionsFunctionToolCallOutput; + | ChatCompletionsToolCallOutputParent + | ChatCompletionsFunctionToolCallOutput; /** An abstract representation of structured information about why a chat completions response terminated. */ export type ChatFinishDetailsOutput = + | ChatFinishDetailsOutputParent | StopFinishDetailsOutput | MaxTokensFinishDetailsOutput; diff --git a/sdk/openai/openai/sources/generated/src/rest/parameters.ts b/sdk/openai/openai/generated/rest/parameters.ts similarity index 83% rename from sdk/openai/openai/sources/generated/src/rest/parameters.ts rename to sdk/openai/openai/generated/rest/parameters.ts index d953111d8be3..3d0c994d76f0 100644 --- a/sdk/openai/openai/sources/generated/src/rest/parameters.ts +++ b/sdk/openai/openai/generated/rest/parameters.ts @@ -15,8 +15,8 @@ export interface GetAudioTranscriptionAsPlainTextBodyParam { body?: AudioTranscriptionOptions; } -export type GetAudioTranscriptionAsPlainTextParameters = - GetAudioTranscriptionAsPlainTextBodyParam & RequestParameters; +export type GetAudioTranscriptionAsPlainTextParameters = GetAudioTranscriptionAsPlainTextBodyParam & + RequestParameters; export interface GetAudioTranscriptionAsResponseObjectBodyParam { body?: AudioTranscriptionOptions; @@ -36,8 +36,8 @@ export interface GetAudioTranslationAsPlainTextBodyParam { body?: AudioTranslationOptions; } -export type GetAudioTranslationAsPlainTextParameters = - GetAudioTranslationAsPlainTextBodyParam & RequestParameters; +export type GetAudioTranslationAsPlainTextParameters = GetAudioTranslationAsPlainTextBodyParam & + RequestParameters; export interface GetAudioTranslationAsResponseObjectBodyParam { body?: AudioTranslationOptions; @@ -57,15 +57,13 @@ export interface GetCompletionsBodyParam { body?: CompletionsOptions; } -export type GetCompletionsParameters = GetCompletionsBodyParam & - RequestParameters; +export type GetCompletionsParameters = GetCompletionsBodyParam & RequestParameters; export interface GetChatCompletionsBodyParam { body?: ChatCompletionsOptions; } -export type GetChatCompletionsParameters = GetChatCompletionsBodyParam & - RequestParameters; +export type GetChatCompletionsParameters = GetChatCompletionsBodyParam & RequestParameters; export interface GetChatCompletionsWithAzureExtensionsBodyParam { body?: ChatCompletionsOptions; @@ -78,21 +76,18 @@ export interface GetImageGenerationsBodyParam { body?: ImageGenerationOptions; } -export type GetImageGenerationsParameters = GetImageGenerationsBodyParam & - RequestParameters; +export type GetImageGenerationsParameters = GetImageGenerationsBodyParam & RequestParameters; export interface GetEmbeddingsBodyParam { body?: EmbeddingsOptions; } -export type GetEmbeddingsParameters = GetEmbeddingsBodyParam & - RequestParameters; -export type GetAzureBatchImageGenerationOperationStatusParameters = - RequestParameters; +export type GetEmbeddingsParameters = GetEmbeddingsBodyParam & RequestParameters; +export type GetAzureBatchImageGenerationOperationStatusParameters = RequestParameters; export interface BeginAzureBatchImageGenerationBodyParam { body?: ImageGenerationOptions; } -export type BeginAzureBatchImageGenerationParameters = - BeginAzureBatchImageGenerationBodyParam & RequestParameters; +export type BeginAzureBatchImageGenerationParameters = BeginAzureBatchImageGenerationBodyParam & + RequestParameters; diff --git a/sdk/openai/openai/generated/rest/pollingHelper.ts b/sdk/openai/openai/generated/rest/pollingHelper.ts new file mode 100644 index 000000000000..1f4888180781 --- /dev/null +++ b/sdk/openai/openai/generated/rest/pollingHelper.ts @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { Client, HttpResponse } from "@azure-rest/core-client"; +import { + CreateHttpPollerOptions, + LongRunningOperation, + LroResponse, + OperationState, + SimplePollerLike, + createHttpPoller, +} from "@azure/core-lro"; +import { + BeginAzureBatchImageGeneration202Response, + BeginAzureBatchImageGenerationDefaultResponse, + BeginAzureBatchImageGenerationLogicalResponse, +} from "./responses.js"; +/** + * Helper function that builds a Poller object to help polling a long running operation. + * @param client - Client to use for sending the request to get additional pages. + * @param initialResponse - The initial response. + * @param options - Options to set a resume state or custom polling interval. + * @returns - A poller object to poll for operation state updates and eventually get the final response. + */ +export async function getLongRunningPoller< + TResult extends + | BeginAzureBatchImageGenerationLogicalResponse + | BeginAzureBatchImageGenerationDefaultResponse, +>( + client: Client, + initialResponse: + | BeginAzureBatchImageGeneration202Response + | BeginAzureBatchImageGenerationDefaultResponse, + options?: CreateHttpPollerOptions>, +): Promise, TResult>>; +export async function getLongRunningPoller( + client: Client, + initialResponse: TResult, + options: CreateHttpPollerOptions> = {}, +): Promise, TResult>> { + const poller: LongRunningOperation = { + requestMethod: initialResponse.request.method, + requestPath: initialResponse.request.url, + sendInitialRequest: async () => { + // In the case of Rest Clients we are building the LRO poller object from a response that's the reason + // we are not triggering the initial request here, just extracting the information from the + // response we were provided. + return getLroResponse(initialResponse); + }, + sendPollRequest: async (path) => { + // This is the callback that is going to be called to poll the service + // to get the latest status. We use the client provided and the polling path + // which is an opaque URL provided by caller, the service sends this in one of the following headers: operation-location, azure-asyncoperation or location + // depending on the lro pattern that the service implements. If non is provided we default to the initial path. + const response = await client.pathUnchecked(path ?? initialResponse.request.url).get(); + const lroResponse = getLroResponse(response as TResult); + lroResponse.rawResponse.headers["x-ms-original-url"] = initialResponse.request.url; + return lroResponse; + }, + }; + + options.resolveOnUnsuccessful = options.resolveOnUnsuccessful ?? true; + return createHttpPoller(poller, options); +} + +/** + * Converts a Rest Client response to a response that the LRO implementation understands + * @param response - a rest client http response + * @returns - An LRO response that the LRO implementation understands + */ +function getLroResponse(response: TResult): LroResponse { + if (Number.isNaN(response.status)) { + throw new TypeError(`Status code of the response is not a number. Value: ${response.status}`); + } + + return { + flatResponse: response, + rawResponse: { + ...response, + statusCode: Number.parseInt(response.status), + body: response.body, + }, + }; +} diff --git a/sdk/openai/openai/sources/generated/src/rest/responses.ts b/sdk/openai/openai/generated/rest/responses.ts similarity index 85% rename from sdk/openai/openai/sources/generated/src/rest/responses.ts rename to sdk/openai/openai/generated/rest/responses.ts index 597f0b154285..c7087c38d32b 100644 --- a/sdk/openai/openai/sources/generated/src/rest/responses.ts +++ b/sdk/openai/openai/generated/rest/responses.ts @@ -14,8 +14,7 @@ import { } from "./outputModels.js"; /** The request has succeeded. */ -export interface GetAudioTranscriptionAsPlainText200Response - extends HttpResponse { +export interface GetAudioTranscriptionAsPlainText200Response extends HttpResponse { status: "200"; body: string; } @@ -25,16 +24,14 @@ export interface GetAudioTranscriptionAsPlainTextDefaultHeaders { "x-ms-error-code"?: string; } -export interface GetAudioTranscriptionAsPlainTextDefaultResponse - extends HttpResponse { +export interface GetAudioTranscriptionAsPlainTextDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & GetAudioTranscriptionAsPlainTextDefaultHeaders; } /** The request has succeeded. */ -export interface GetAudioTranscriptionAsResponseObject200Response - extends HttpResponse { +export interface GetAudioTranscriptionAsResponseObject200Response extends HttpResponse { status: "200"; body: AudioTranscriptionOutput; } @@ -44,16 +41,14 @@ export interface GetAudioTranscriptionAsResponseObjectDefaultHeaders { "x-ms-error-code"?: string; } -export interface GetAudioTranscriptionAsResponseObjectDefaultResponse - extends HttpResponse { +export interface GetAudioTranscriptionAsResponseObjectDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & GetAudioTranscriptionAsResponseObjectDefaultHeaders; } /** The request has succeeded. */ -export interface GetAudioTranslationAsPlainText200Response - extends HttpResponse { +export interface GetAudioTranslationAsPlainText200Response extends HttpResponse { status: "200"; body: string; } @@ -63,16 +58,14 @@ export interface GetAudioTranslationAsPlainTextDefaultHeaders { "x-ms-error-code"?: string; } -export interface GetAudioTranslationAsPlainTextDefaultResponse - extends HttpResponse { +export interface GetAudioTranslationAsPlainTextDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & GetAudioTranslationAsPlainTextDefaultHeaders; } /** The request has succeeded. */ -export interface GetAudioTranslationAsResponseObject200Response - extends HttpResponse { +export interface GetAudioTranslationAsResponseObject200Response extends HttpResponse { status: "200"; body: AudioTranslationOutput; } @@ -82,8 +75,7 @@ export interface GetAudioTranslationAsResponseObjectDefaultHeaders { "x-ms-error-code"?: string; } -export interface GetAudioTranslationAsResponseObjectDefaultResponse - extends HttpResponse { +export interface GetAudioTranslationAsResponseObjectDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & GetAudioTranslationAsResponseObjectDefaultHeaders; @@ -124,8 +116,7 @@ export interface GetChatCompletionsDefaultResponse extends HttpResponse { } /** The request has succeeded. */ -export interface GetChatCompletionsWithAzureExtensions200Response - extends HttpResponse { +export interface GetChatCompletionsWithAzureExtensions200Response extends HttpResponse { status: "200"; body: ChatCompletionsOutput; } @@ -135,8 +126,7 @@ export interface GetChatCompletionsWithAzureExtensionsDefaultHeaders { "x-ms-error-code"?: string; } -export interface GetChatCompletionsWithAzureExtensionsDefaultResponse - extends HttpResponse { +export interface GetChatCompletionsWithAzureExtensionsDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & GetChatCompletionsWithAzureExtensionsDefaultHeaders; @@ -177,8 +167,7 @@ export interface GetEmbeddingsDefaultResponse extends HttpResponse { } /** The request has succeeded. */ -export interface GetAzureBatchImageGenerationOperationStatus200Response - extends HttpResponse { +export interface GetAzureBatchImageGenerationOperationStatus200Response extends HttpResponse { status: "200"; body: BatchImageGenerationOperationResponseOutput; } @@ -188,12 +177,10 @@ export interface GetAzureBatchImageGenerationOperationStatusDefaultHeaders { "x-ms-error-code"?: string; } -export interface GetAzureBatchImageGenerationOperationStatusDefaultResponse - extends HttpResponse { +export interface GetAzureBatchImageGenerationOperationStatusDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; - headers: RawHttpHeaders & - GetAzureBatchImageGenerationOperationStatusDefaultHeaders; + headers: RawHttpHeaders & GetAzureBatchImageGenerationOperationStatusDefaultHeaders; } export interface BeginAzureBatchImageGeneration202Headers { @@ -202,8 +189,7 @@ export interface BeginAzureBatchImageGeneration202Headers { } /** The request has been accepted for processing, but processing has not yet completed. */ -export interface BeginAzureBatchImageGeneration202Response - extends HttpResponse { +export interface BeginAzureBatchImageGeneration202Response extends HttpResponse { status: "202"; body: BatchImageGenerationOperationResponseOutput; headers: RawHttpHeaders & BeginAzureBatchImageGeneration202Headers; @@ -214,16 +200,14 @@ export interface BeginAzureBatchImageGenerationDefaultHeaders { "x-ms-error-code"?: string; } -export interface BeginAzureBatchImageGenerationDefaultResponse - extends HttpResponse { +export interface BeginAzureBatchImageGenerationDefaultResponse extends HttpResponse { status: string; body: ErrorResponse; headers: RawHttpHeaders & BeginAzureBatchImageGenerationDefaultHeaders; } /** The final response for long-running beginAzureBatchImageGeneration operation */ -export interface BeginAzureBatchImageGenerationLogicalResponse - extends HttpResponse { +export interface BeginAzureBatchImageGenerationLogicalResponse extends HttpResponse { status: "200"; body: BatchImageGenerationOperationResponseOutput; } diff --git a/sdk/openai/openai/generated/utils/serializeUtil.ts b/sdk/openai/openai/generated/utils/serializeUtil.ts new file mode 100644 index 000000000000..4d60994d46f4 --- /dev/null +++ b/sdk/openai/openai/generated/utils/serializeUtil.ts @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + ChatRequestUserMessage as ChatRequestUserMessageRest, + ChatRequestAssistantMessage as ChatRequestAssistantMessageRest, + ChatRequestToolMessage as ChatRequestToolMessageRest, + ChatRequestMessage as ChatRequestMessageRest, + ChatMessageImageContentItem as ChatMessageImageContentItemRest, + ChatMessageContentItem as ChatMessageContentItemRest, +} from "../rest/index.js"; +import { + ChatRequestUserMessage, + ChatRequestAssistantMessage, + ChatRequestToolMessage, + ChatRequestMessageUnion, + ChatMessageImageContentItem, + ChatMessageContentItemUnion, +} from "../models/models.js"; + +/** serialize function for ChatRequestUserMessage */ +function serializeChatRequestUserMessage(obj: ChatRequestUserMessage): ChatRequestUserMessageRest { + return { + role: obj["role"], + content: obj["content"] as any, + name: obj["name"], + }; +} + +/** serialize function for ChatRequestAssistantMessage */ +function serializeChatRequestAssistantMessage( + obj: ChatRequestAssistantMessage, +): ChatRequestAssistantMessageRest { + return { + role: obj["role"], + content: obj["content"], + name: obj["name"], + tool_calls: obj["toolCalls"], + function_call: !obj.functionCall + ? undefined + : { + name: obj.functionCall?.["name"], + arguments: obj.functionCall?.["arguments"], + }, + }; +} + +/** serialize function for ChatRequestToolMessage */ +function serializeChatRequestToolMessage(obj: ChatRequestToolMessage): ChatRequestToolMessageRest { + return { + role: obj["role"], + content: obj["content"], + tool_call_id: obj["toolCallId"], + }; +} + +/** serialize function for ChatRequestMessageUnion */ +export function serializeChatRequestMessageUnion( + obj: ChatRequestMessageUnion, +): ChatRequestMessageRest { + switch (obj.role) { + case "user": + return serializeChatRequestUserMessage(obj as ChatRequestUserMessage); + case "assistant": + return serializeChatRequestAssistantMessage(obj as ChatRequestAssistantMessage); + case "tool": + return serializeChatRequestToolMessage(obj as ChatRequestToolMessage); + default: + return obj; + } +} + +/** serialize function for ChatMessageImageContentItem */ +function serializeChatMessageImageContentItem( + obj: ChatMessageImageContentItem, +): ChatMessageImageContentItemRest { + return { + type: obj["type"], + image_url: { url: obj.imageUrl["url"], detail: obj.imageUrl["detail"] }, + }; +} + +/** serialize function for ChatMessageContentItemUnion */ +export function serializeChatMessageContentItemUnion( + obj: ChatMessageContentItemUnion, +): ChatMessageContentItemRest { + switch (obj.type) { + case "image_url": + return serializeChatMessageImageContentItem(obj as ChatMessageImageContentItem); + default: + return obj; + } +} diff --git a/sdk/openai/openai/package.json b/sdk/openai/openai/package.json index c1625a2fb57f..d7aeea371f14 100644 --- a/sdk/openai/openai/package.json +++ b/sdk/openai/openai/package.json @@ -50,12 +50,12 @@ "clean": "rimraf --glob dist dist-* temp types *.tgz *.log", "execute:samples": "dev-tool samples run samples-dev", "extract-api": "tsc -p . && api-extractor run --local", - "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"sources/customizations/**/*.ts\" \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", + "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"generated/**/*.ts\" \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"", "integration-test:browser": "npm run unit-test:browser", "integration-test:node": "dev-tool run test:node-js-input -- --timeout 5000000 \"dist-esm/test/public/{,!(browser)/**/}/*.spec.js\"", "integration-test": "npm run integration-test:node && npm run integration-test:browser", - "lint:fix": "eslint README.md package.json api-extractor.json sources src test --ext .ts,.javascript,.js --fix --fix-type [problem,suggestion]", - "lint": "eslint README.md package.json api-extractor.json sources src test --ext .ts,.javascript,.js", + "lint:fix": "eslint README.md package.json api-extractor.json src test --ext .ts,.javascript,.js --fix --fix-type [problem,suggestion]", + "lint": "eslint README.md package.json api-extractor.json src test --ext .ts,.javascript,.js", "pack": "npm pack 2>&1", "test:browser": "npm run clean && npm run build && npm run integration-test:browser", "test:node": "npm run clean && tsc -p . && npm run integration-test:node", diff --git a/sdk/openai/openai/review/openai.api.md b/sdk/openai/openai/review/openai.api.md index 47152130509c..8ae9da3ddfb6 100644 --- a/sdk/openai/openai/review/openai.api.md +++ b/sdk/openai/openai/review/openai.api.md @@ -95,8 +95,8 @@ export interface AzureChatOCREnhancementConfiguration { // @public export interface AzureCognitiveSearchChatExtensionConfiguration { - authentication?: OnYourDataAuthenticationOptions; - embeddingDependency?: OnYourDataVectorizationSource; + authentication?: OnYourDataAuthenticationOptionsUnion; + embeddingDependency?: OnYourDataVectorizationSourceUnion; embeddingEndpoint?: string; embeddingKey?: string; endpoint: string; @@ -125,14 +125,14 @@ export interface AzureCognitiveSearchIndexFieldMappingOptions { } // @public -export type AzureCognitiveSearchQueryType = "simple" | "semantic" | "vector" | "vectorSimpleHybrid" | "vectorSemanticHybrid"; +export type AzureCognitiveSearchQueryType = string; // @public export interface AzureCosmosDBChatExtensionConfiguration { - authentication?: OnYourDataAuthenticationOptions; + authentication?: OnYourDataAuthenticationOptionsUnion; containerName: string; databaseName: string; - embeddingDependency?: OnYourDataVectorizationSource; + embeddingDependency?: OnYourDataVectorizationSourceUnion; fieldsMapping: AzureCosmosDBFieldMappingOptions; indexName: string; inScope?: boolean; @@ -182,7 +182,7 @@ export { AzureKeyCredential } // @public export interface AzureMachineLearningIndexChatExtensionConfiguration { - authentication?: OnYourDataAuthenticationOptions; + authentication?: OnYourDataAuthenticationOptionsUnion; filter?: string; inScope?: boolean; name: string; @@ -199,7 +199,7 @@ export interface ChatChoice { contentFilterResults?: ContentFilterResultsForChoice; delta?: ChatResponseMessage; enhancements?: AzureChatEnhancements; - finishDetails?: ChatFinishDetails; + finishDetails?: ChatFinishDetailsUnion; finishReason: CompletionsFinishReason | null; index: number; message?: ChatResponseMessage; @@ -216,66 +216,94 @@ export interface ChatCompletions { } // @public -export interface ChatCompletionsFunctionToolCall { +export interface ChatCompletionsFunctionToolCall extends ChatCompletionsToolCall { function: FunctionCall; - id: string; - index?: number; type: "function"; } // @public -export interface ChatCompletionsFunctionToolDefinition { +export interface ChatCompletionsFunctionToolDefinition extends ChatCompletionsToolDefinition { function: FunctionDefinition; type: "function"; } // @public -export interface ChatCompletionsJsonResponseFormat { +export interface ChatCompletionsJsonResponseFormat extends ChatCompletionsResponseFormat { type: "json_object"; } // @public -export interface ChatCompletionsNamedFunctionToolSelection { - function: { - name: string; - }; +export interface ChatCompletionsNamedFunctionToolSelection extends ChatCompletionsNamedToolSelection { + name: string; type: "function"; } // @public -export type ChatCompletionsNamedToolSelection = ChatCompletionsToolSelectionPreset | ChatCompletionsNamedFunctionToolSelection; +export interface ChatCompletionsNamedToolSelection { + type: string; +} + +// @public +export type ChatCompletionsNamedToolSelectionUnion = ChatCompletionsNamedFunctionToolSelection | ChatCompletionsToolSelectionPreset | ChatCompletionsNamedToolSelection; // @public -export type ChatCompletionsResponseFormat = ChatCompletionsTextResponseFormat | ChatCompletionsJsonResponseFormat; +export interface ChatCompletionsResponseFormat { + type: string; +} // @public -export interface ChatCompletionsTextResponseFormat { +export type ChatCompletionsResponseFormatUnion = ChatCompletionsTextResponseFormat | ChatCompletionsJsonResponseFormat | ChatCompletionsResponseFormat; + +// @public +export interface ChatCompletionsTextResponseFormat extends ChatCompletionsResponseFormat { type: "text"; } // @public -export type ChatCompletionsToolCall = ChatCompletionsFunctionToolCall; +export interface ChatCompletionsToolCall { + id: string; + index?: number; + type: string; +} + +// @public +export type ChatCompletionsToolCallUnion = ChatCompletionsFunctionToolCall | ChatCompletionsToolCall; + +// @public +export interface ChatCompletionsToolDefinition { + type: string; +} + +// @public +export type ChatCompletionsToolDefinitionUnion = ChatCompletionsFunctionToolDefinition | ChatCompletionsToolDefinition; + +// @public +export type ChatCompletionsToolSelectionPreset = string; // @public -export type ChatCompletionsToolDefinition = ChatCompletionsFunctionToolDefinition; +export interface ChatFinishDetails { + type: string; +} // @public -export type ChatCompletionsToolSelectionPreset = "auto" | "none"; +export type ChatFinishDetailsUnion = StopFinishDetails | MaxTokensFinishDetails | ChatFinishDetails; // @public -export type ChatFinishDetails = StopFinishDetails | MaxTokensFinishDetails; +export interface ChatMessageContentItem { + type: string; +} // @public -export type ChatMessageContentItem = ChatMessageTextContentItem | ChatMessageImageContentItem; +export type ChatMessageContentItemUnion = ChatMessageTextContentItem | ChatMessageImageContentItem | ChatMessageContentItem; // @public -export interface ChatMessageImageContentItem { +export interface ChatMessageImageContentItem extends ChatMessageContentItem { imageUrl: ChatMessageImageUrl; type: "image_url"; } // @public -export type ChatMessageImageDetailLevel = "auto" | "low" | "high"; +export type ChatMessageImageDetailLevel = string; // @public export interface ChatMessageImageUrl { @@ -284,47 +312,52 @@ export interface ChatMessageImageUrl { } // @public -export interface ChatMessageTextContentItem { +export interface ChatMessageTextContentItem extends ChatMessageContentItem { text: string; type: "text"; } // @public -export interface ChatRequestAssistantMessage { +export interface ChatRequestAssistantMessage extends ChatRequestMessage { content: string | null; functionCall?: FunctionCall; name?: string; role: "assistant"; - toolCalls?: Array; + toolCalls?: ChatCompletionsToolCallUnion[]; } // @public -export interface ChatRequestFunctionMessage { +export interface ChatRequestFunctionMessage extends ChatRequestMessage { content: string | null; name: string; role: "function"; } // @public -export type ChatRequestMessage = ChatRequestSystemMessage | ChatRequestUserMessage | ChatRequestAssistantMessage | ChatRequestToolMessage | ChatRequestFunctionMessage; +export interface ChatRequestMessage { + role: ChatRole; +} + +// @public +export type ChatRequestMessageUnion = ChatRequestSystemMessage | ChatRequestUserMessage | ChatRequestAssistantMessage | ChatRequestToolMessage | ChatRequestFunctionMessage | ChatRequestMessage; // @public -export interface ChatRequestSystemMessage { +export interface ChatRequestSystemMessage extends ChatRequestMessage { content: string; name?: string; role: "system"; } // @public -export interface ChatRequestToolMessage { +export interface ChatRequestToolMessage extends ChatRequestMessage { content: string | null; role: "tool"; toolCallId: string; } // @public -export interface ChatRequestUserMessage { - content: string | Array; +export interface ChatRequestUserMessage extends ChatRequestMessage { + content: string | ChatMessageContentItemUnion[]; name?: string; role: "user"; } @@ -335,7 +368,7 @@ export interface ChatResponseMessage { context?: AzureChatExtensionsMessageContext; functionCall?: FunctionCall; role: ChatRole; - toolCalls: ChatCompletionsToolCall[]; + toolCalls: ChatCompletionsToolCallUnion[]; } // @public @@ -458,8 +491,8 @@ export interface ContentFilterSuccessResultsForChoice { // @public export interface ElasticsearchChatExtensionConfiguration { - authentication?: OnYourDataAuthenticationOptions; - embeddingDependency?: OnYourDataVectorizationSource; + authentication?: OnYourDataAuthenticationOptionsUnion; + embeddingDependency?: OnYourDataVectorizationSourceUnion; endpoint: string; fieldsMapping?: ElasticsearchIndexFieldMappingOptions; indexName: string; @@ -482,7 +515,7 @@ export interface ElasticsearchIndexFieldMappingOptions { } // @public -export type ElasticsearchQueryType = "simple" | "vector"; +export type ElasticsearchQueryType = string; // @public export interface EmbeddingItem { @@ -513,7 +546,7 @@ export interface FunctionCall { } // @public -export type FunctionCallPreset = "auto" | "none"; +export type FunctionCallPreset = string; // @public export interface FunctionDefinition { @@ -554,8 +587,8 @@ export interface GetChatCompletionsOptions extends OperationOptions { seed?: number; stop?: string[]; temperature?: number; - toolChoice?: ChatCompletionsNamedToolSelection; - tools?: ChatCompletionsToolDefinition[]; + toolChoice?: ChatCompletionsNamedToolSelectionUnion; + tools?: ChatCompletionsToolDefinitionUnion[]; topP?: number; user?: string; } @@ -600,10 +633,10 @@ export interface ImageGenerationData { } // @public -export type ImageGenerationQuality = "standard" | "hd"; +export type ImageGenerationQuality = string; // @public -export type ImageGenerationResponseFormat = "url" | "b64_json"; +export type ImageGenerationResponseFormat = string; // @public export interface ImageGenerations { @@ -612,76 +645,86 @@ export interface ImageGenerations { } // @public -export type ImageGenerationStyle = "natural" | "vivid"; +export type ImageGenerationStyle = string; // @public -export type ImageSize = "1024x1024" | "1792x1024" | "1024x1792"; +export type ImageSize = string; // @public -export interface MaxTokensFinishDetails { +export interface MaxTokensFinishDetails extends ChatFinishDetails { type: "max_tokens"; } // @public -export interface OnYourDataApiKeyAuthenticationOptions { +export interface OnYourDataApiKeyAuthenticationOptions extends OnYourDataAuthenticationOptions { key: string; type: "APIKey"; } // @public -export type OnYourDataAuthenticationOptions = OnYourDataApiKeyAuthenticationOptions | OnYourDataConnectionStringAuthenticationOptions | OnYourDataKeyAndKeyIdAuthenticationOptions | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions | OnYourDataUserAssignedManagedIdentityAuthenticationOptions; +export interface OnYourDataAuthenticationOptions { + type: OnYourDataAuthenticationType; +} + +// @public +export type OnYourDataAuthenticationOptionsUnion = OnYourDataApiKeyAuthenticationOptions | OnYourDataConnectionStringAuthenticationOptions | OnYourDataKeyAndKeyIdAuthenticationOptions | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions | OnYourDataUserAssignedManagedIdentityAuthenticationOptions | OnYourDataAuthenticationOptions; // @public -export type OnYourDataAuthenticationType = "APIKey" | "ConnectionString" | "KeyAndKeyId" | "SystemAssignedManagedIdentity" | "UserAssignedManagedIdentity"; +export type OnYourDataAuthenticationType = string; // @public -export interface OnYourDataConnectionStringAuthenticationOptions { +export interface OnYourDataConnectionStringAuthenticationOptions extends OnYourDataAuthenticationOptions { connectionString: string; type: "ConnectionString"; } // @public -export interface OnYourDataDeploymentNameVectorizationSource { +export interface OnYourDataDeploymentNameVectorizationSource extends OnYourDataVectorizationSource { deploymentName: string; type: "DeploymentName"; } // @public -export interface OnYourDataEndpointVectorizationSource { - authentication: OnYourDataAuthenticationOptions; +export interface OnYourDataEndpointVectorizationSource extends OnYourDataVectorizationSource { + authentication: OnYourDataAuthenticationOptionsUnion; endpoint: string; type: "Endpoint"; } // @public -export interface OnYourDataKeyAndKeyIdAuthenticationOptions { +export interface OnYourDataKeyAndKeyIdAuthenticationOptions extends OnYourDataAuthenticationOptions { key: string; keyId: string; type: "KeyAndKeyId"; } // @public -export interface OnYourDataModelIdVectorizationSource { +export interface OnYourDataModelIdVectorizationSource extends OnYourDataVectorizationSource { modelId: string; type: "ModelId"; } // @public -export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions { +export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions extends OnYourDataAuthenticationOptions { type: "SystemAssignedManagedIdentity"; } // @public -export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions { +export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions extends OnYourDataAuthenticationOptions { managedIdentityResourceId: string; type: "UserAssignedManagedIdentity"; } // @public -export type OnYourDataVectorizationSource = OnYourDataEndpointVectorizationSource | OnYourDataDeploymentNameVectorizationSource | OnYourDataModelIdVectorizationSource; +export interface OnYourDataVectorizationSource { + type: OnYourDataVectorizationSourceType; +} + +// @public +export type OnYourDataVectorizationSourceType = string; // @public -export type OnYourDataVectorizationSourceType = "Endpoint" | "DeploymentName" | "ModelId"; +export type OnYourDataVectorizationSourceUnion = OnYourDataEndpointVectorizationSource | OnYourDataDeploymentNameVectorizationSource | OnYourDataModelIdVectorizationSource | OnYourDataVectorizationSource; // @public export class OpenAIClient { @@ -692,11 +735,11 @@ export class OpenAIClient { getAudioTranscription(deploymentName: string, fileContent: Uint8Array, format: Format, options?: GetAudioTranscriptionOptions): Promise>; getAudioTranslation(deploymentName: string, fileContent: Uint8Array, options?: GetAudioTranslationOptions): Promise; getAudioTranslation(deploymentName: string, fileContent: Uint8Array, format: Format, options?: GetAudioTranslationOptions): Promise>; - getChatCompletions(deploymentName: string, messages: ChatRequestMessage[], options?: GetChatCompletionsOptions): Promise; + getChatCompletions(deploymentName: string, messages: ChatRequestMessageUnion[], options?: GetChatCompletionsOptions): Promise; getCompletions(deploymentName: string, prompt: string[], options?: GetCompletionsOptions): Promise; getEmbeddings(deploymentName: string, input: string[], options?: GetEmbeddingsOptions): Promise; getImages(deploymentName: string, prompt: string, options?: GetImagesOptions): Promise; - streamChatCompletions(deploymentName: string, messages: ChatRequestMessage[], options?: GetChatCompletionsOptions): Promise>; + streamChatCompletions(deploymentName: string, messages: ChatRequestMessageUnion[], options?: GetChatCompletionsOptions): Promise>; streamCompletions(deploymentName: string, prompt: string[], options?: GetCompletionsOptions): Promise>>; } @@ -737,7 +780,7 @@ export interface PineconeFieldMappingOptions { } // @public -export interface StopFinishDetails { +export interface StopFinishDetails extends ChatFinishDetails { stop: string; type: "stop"; } diff --git a/sdk/openai/openai/sources/customizations/OpenAIClient.ts b/sdk/openai/openai/sources/customizations/OpenAIClient.ts deleted file mode 100644 index e1115f794a09..000000000000 --- a/sdk/openai/openai/sources/customizations/OpenAIClient.ts +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { TokenCredential, KeyCredential, isTokenCredential } from "@azure/core-auth"; -import { OpenAIClientOptions } from "../generated/src/index.js"; -import { - getAudioTranscription, - getAudioTranslation, - getChatCompletions, - getCompletions, - getImages, - streamChatCompletions, - streamCompletions, -} from "./api/client/openAIClient/index.js"; -import { Embeddings, ImageGenerations } from "../generated/src/models/models.js"; -import { getEmbeddings } from "../generated/src/api/client/openAIClient/index.js"; -import { OpenAIContext } from "../generated/src/rest/index.js"; -import { createOpenAI } from "../generated/src/api/OpenAIContext.js"; -import { - GetImagesOptions, - GetCompletionsOptions, - GetEmbeddingsOptions, - GetChatCompletionsOptions, -} from "./models/options.js"; -import { nonAzurePolicy } from "./api/policies/nonAzure.js"; -import { - AudioResult, - AudioResultFormat, - AudioResultSimpleJson, - GetAudioTranscriptionOptions, - GetAudioTranslationOptions, -} from "./models/audio.js"; -import { ChatCompletions, ChatRequestMessage, Completions, EventStream } from "./models/models.js"; - -function createOpenAIEndpoint(version: number): string { - return `https://api.openai.com/v${version}`; -} - -function isCred(cred: Record): cred is TokenCredential | KeyCredential { - return isTokenCredential(cred) || cred.key !== undefined; -} - -/** - * A client for interacting with Azure OpenAI. - * - * The client needs the endpoint of an OpenAI resource and an authentication - * method such as an API key or token. The API key and endpoint can be found in - * the OpenAI resource page. They will be located in the resource's Keys and Endpoint page. - * - * ### Examples for authentication: - * - * #### API Key - * - * ```js - * import { OpenAIClient } from "@azure/openai"; - * import { AzureKeyCredential } from "@azure/core-auth"; - * - * const endpoint = ""; - * const credential = new AzureKeyCredential(""); - * - * const client = new OpenAIClient(endpoint, credential); - * ``` - * - * #### Azure Active Directory - * - * ```js - * import { OpenAIClient } from "@azure/openai"; - * import { DefaultAzureCredential } from "@azure/identity"; - * - * const endpoint = ""; - * const credential = new DefaultAzureCredential(); - * - * const client = new OpenAIClient(endpoint, credential); - * ``` - */ -export class OpenAIClient { - private _client: OpenAIContext; - private _isAzure = false; - - /** - * Initializes an instance of OpenAIClient for use with an Azure OpenAI resource. - * @param endpoint - The URI for an Azure OpenAI resource, including protocol and hostname. - * For example: https://my-resource.openai.azure.com. - * @param credential - A key credential used to authenticate to an Azure OpenAI resource. - * @param options - The options for configuring the client. - * @remarks - * This constructor initializes an OpenAIClient object that can only be used with Azure OpenAI resources. - * To use OpenAIClient with a non-Azure OpenAI inference endpoint, use a constructor that accepts a non-Azure OpenAI API key instead. - */ - constructor(endpoint: string, credential: KeyCredential, options?: OpenAIClientOptions); - /** - * Initializes an instance of OpenAIClient for use with an Azure OpenAI resource. - * @param endpoint - The URI for an Azure OpenAI resource, including protocol and hostname. - * For example: https://my-resource.openai.azure.com. - * @param credential - A token credential used to authenticate with an Azure OpenAI resource. - * @param options - The options for configuring the client. - */ - constructor(endpoint: string, credential: TokenCredential, options?: OpenAIClientOptions); - /** - * Initializes an instance of OpenAIClient for use with the non-Azure OpenAI endpoint. - * @param openAiApiKey - The API key to use when connecting to the non-Azure OpenAI endpoint. - * @param options - The options for configuring the client. - * @remarks - * OpenAIClient objects initialized with this constructor can only be used with the non-Azure OpenAI inference endpoint. - * To use OpenAIClient with an Azure OpenAI resource, use a constructor that accepts a resource URI and Azure authentication credential instead. - */ - constructor(openAiApiKey: KeyCredential, options?: OpenAIClientOptions); - constructor( - endpointOrOpenAiKey: string | KeyCredential, - credOrOptions: KeyCredential | TokenCredential | OpenAIClientOptions = {}, - options: OpenAIClientOptions = {}, - ) { - let opts: OpenAIClientOptions; - let endpoint: string; - let cred: KeyCredential | TokenCredential; - if (isCred(credOrOptions)) { - endpoint = endpointOrOpenAiKey as string; - cred = credOrOptions; - opts = options; - this._isAzure = true; - } else { - endpoint = createOpenAIEndpoint(1); - cred = endpointOrOpenAiKey as KeyCredential; - const { credentials, ...restOpts } = credOrOptions; - opts = { - credentials: { - apiKeyHeaderName: credentials?.apiKeyHeaderName ?? "Authorization", - scopes: credentials?.scopes, - }, - ...restOpts, - }; - } - this._client = createOpenAI(endpoint, cred, { - ...opts, - ...(this._isAzure - ? {} - : { - additionalPolicies: [ - ...(opts.additionalPolicies ?? []), - { - position: "perCall", - policy: nonAzurePolicy(), - }, - ], - }), - }); - } - - private setModel(model: string, options: Record): void { - if (!this._isAzure) { - options.model = model; - } - } - - /** - * Returns textual completions as configured for a given prompt. - * @param deploymentName - Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param prompt - The prompt to use for this request. - * @param options - The options for this completions request. - * @returns The completions for the given prompt. - */ - getCompletions( - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = { requestOptions: {} }, - ): Promise { - this.setModel(deploymentName, options); - return getCompletions(this._client, deploymentName, prompt, options); - } - - /** - * Lists the completions tokens as they become available for a given prompt. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param prompt - The prompt to use for this request. - * @param options - The completions options for this completions request. - * @returns An asynchronous iterable of completions tokens. - */ - streamCompletions( - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = {}, - ): Promise>> { - this.setModel(deploymentName, options); - return streamCompletions(this._client, deploymentName, prompt, options); - } - - /** - * Return the computed embeddings for a given prompt. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param input - The prompt to use for this request. - * @param options - The embeddings options for this embeddings request. - * @returns The embeddings for the given prompt. - */ - getEmbeddings( - deploymentName: string, - input: string[], - options: GetEmbeddingsOptions = { requestOptions: {} }, - ): Promise { - this.setModel(deploymentName, options); - return getEmbeddings(this._client, deploymentName, { input, ...options }, options); - } - - /** - * Get chat completions for provided chat context messages. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param messages - The chat context messages to use for this request. - * @param options - The chat completions options for this completions request. - * @returns The chat completions for the given chat context messages. - */ - getChatCompletions( - deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, - ): Promise { - this.setModel(deploymentName, options); - return getChatCompletions(this._client, deploymentName, messages, options); - } - - /** - * Lists the chat completions tokens as they become available for a chat context. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param messages - The chat context messages to use for this request. - * @param options - The chat completions options for this chat completions request. - * @returns An asynchronous iterable of chat completions tokens. - */ - streamChatCompletions( - deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, - ): Promise> { - this.setModel(deploymentName, options); - return streamChatCompletions(this._client, deploymentName, messages, options); - } - - /** - * Starts the generation of a batch of images from a text caption - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param prompt - The prompt to use for this request. - * @param options - The options for this image request. - * @returns The image generation response (containing url or base64 data). - */ - getImages( - deploymentName: string, - prompt: string, - options: GetImagesOptions = { requestOptions: {} }, - ): Promise { - this.setModel(deploymentName, options); - return getImages(this._client, deploymentName, prompt, options); - } - - /** - * Returns the transcription of an audio file in a simple JSON format. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to transcribe. - * @param options - The options for this audio transcription request. - * @returns The audio transcription result in a simple JSON format. - */ - async getAudioTranscription( - deploymentName: string, - fileContent: Uint8Array, - options?: GetAudioTranscriptionOptions, - ): Promise; - /** - * Returns the transcription of an audio file. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to transcribe. - * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. - * @param options - The options for this audio transcription request. - * @returns The audio transcription result in a format of your choice. - */ - async getAudioTranscription( - deploymentName: string, - fileContent: Uint8Array, - format: Format, - options?: GetAudioTranscriptionOptions, - ): Promise>; - // implementation - async getAudioTranscription( - deploymentName: string, - fileContent: Uint8Array, - formatOrOptions?: Format | GetAudioTranscriptionOptions, - inputOptions?: GetAudioTranscriptionOptions, - ): Promise> { - const options = - inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); - const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; - this.setModel(deploymentName, options); - if (response_format === undefined) { - return getAudioTranscription(this._client, deploymentName, fileContent, options) as Promise< - AudioResult - >; - } - return getAudioTranscription( - this._client, - deploymentName, - fileContent, - response_format, - options, - ); - } - - /** - * Returns the translation of an audio file. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. - * @param options - The options for this audio translation request. - * @returns The audio translation result. - */ - async getAudioTranslation( - deploymentName: string, - fileContent: Uint8Array, - options?: GetAudioTranslationOptions, - ): Promise; - /** - * Returns the translation of an audio file. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. - * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. - * @param options - The options for this audio translation request. - * @returns The audio translation result. - */ - async getAudioTranslation( - deploymentName: string, - fileContent: Uint8Array, - format: Format, - options?: GetAudioTranslationOptions, - ): Promise>; - // implementation - async getAudioTranslation( - deploymentName: string, - fileContent: Uint8Array, - formatOrOptions?: Format | GetAudioTranslationOptions, - inputOptions?: GetAudioTranslationOptions, - ): Promise> { - const options = - inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); - const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; - this.setModel(deploymentName, options); - if (response_format === undefined) { - return getAudioTranslation(this._client, deploymentName, fileContent, options) as Promise< - AudioResult - >; - } - return getAudioTranslation(this._client, deploymentName, fileContent, response_format, options); - } -} diff --git a/sdk/openai/openai/sources/customizations/OpenAIKeyCredential.ts b/sdk/openai/openai/sources/customizations/OpenAIKeyCredential.ts deleted file mode 100644 index 1b783b3c9d26..000000000000 --- a/sdk/openai/openai/sources/customizations/OpenAIKeyCredential.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { KeyCredential } from "@azure/core-auth"; - -function createKey(key: string): string { - return key.startsWith("Bearer ") ? key : `Bearer ${key}`; -} - -/** - * The OpenAIKeyCredential class represents an OpenAI API key - * and is used to authenticate into an OpenAI client for - * an OpenAI endpoint. - */ -export class OpenAIKeyCredential implements KeyCredential { - private _key: string; - - /** - * The value of the key to be used in authentication - */ - public get key(): string { - return this._key; - } - - /** - * Create an instance of an AzureKeyCredential for use - * with a service client. - * - * @param key - The initial value of the key to use in authentication - */ - constructor(key: string) { - if (!key) { - throw new Error("key must be a non-empty string"); - } - - this._key = createKey(key); - } - - /** - * Change the value of the key. - * - * Updates will take effect upon the next request after - * updating the key value. - * - * @param newKey - The new key value to be used - */ - public update(newKey: string): void { - this._key = createKey(newKey); - } -} diff --git a/sdk/openai/openai/sources/customizations/api/client/openAIClient/deserializers.ts b/sdk/openai/openai/sources/customizations/api/client/openAIClient/deserializers.ts deleted file mode 100644 index 2506e7df715a..000000000000 --- a/sdk/openai/openai/sources/customizations/api/client/openAIClient/deserializers.ts +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { ErrorModel } from "@azure-rest/core-client"; -import { - ChatCompletionsOutput, - ChatResponseMessageOutput, - CompletionsOutput, - ContentFilterResultDetailsForPromptOutput, - ContentFilterResultsForChoiceOutput, - ContentFilterResultsForPromptOutput, -} from "../../../../generated/src/rest/outputModels.js"; -import { - ChatCompletions, - ChatResponseMessage, - Completions, - ContentFilterResultDetailsForPrompt, - ContentFilterResultsForChoice, - ContentFilterResultsForPrompt, -} from "../../../models/models.js"; -import { camelCaseKeys } from "../../util.js"; - -type ContentFilterResultsForPromptX = { - prompt_filter_results?: Array; - prompt_annotations?: Array; -}; - -function getContentFilterResultsForPrompt({ - prompt_annotations, - prompt_filter_results, -}: ContentFilterResultsForPromptX): ContentFilterResultsForPrompt[] { - const res = prompt_filter_results ?? prompt_annotations; - return ( - res?.map(({ content_filter_results, ...rest }) => ({ - ...camelCaseKeys(rest), - contentFilterResults: parseContentFilterResultDetailsForPromptOutput(content_filter_results), - })) ?? [] - ); -} - -export function getCompletionsResult( - body: CompletionsOutput & ContentFilterResultsForPromptX, -): Completions { - const { created, choices, prompt_filter_results, prompt_annotations, ...rest } = body; - return { - ...camelCaseKeys(rest), - created: new Date(created), - promptFilterResults: getContentFilterResultsForPrompt({ - prompt_filter_results, - prompt_annotations, - }), - choices: !choices - ? [] - : choices.map(({ content_filter_results, ...choice }) => ({ - ...camelCaseKeys(choice), - ...(!content_filter_results - ? {} - : { - contentFilterResults: - parseContentFilterResultsForChoiceOutput(content_filter_results), - }), - })), - }; -} -export function getChatCompletionsResult( - body: ChatCompletionsOutput & ContentFilterResultsForPromptX, -): ChatCompletions { - const { created, choices, prompt_filter_results, prompt_annotations, ...rest } = body; - return { - ...camelCaseKeys(rest), - created: new Date(created), - promptFilterResults: getContentFilterResultsForPrompt({ - prompt_filter_results, - prompt_annotations, - }), - choices: choices.map(({ content_filter_results, delta, message, ...choice }) => ({ - ...camelCaseKeys(choice), - ...(!delta ? {} : { delta: parseMessage(delta) }), - ...(!message ? {} : { message: parseMessage(message) }), - ...(!content_filter_results - ? {} - : { - contentFilterResults: parseContentFilterResultsForChoiceOutput(content_filter_results), - }), - })), - }; -} - -function parseMessage(message: ChatResponseMessageOutput): ChatResponseMessage { - const { context, tool_calls, ...rest } = message; - return { - ...camelCaseKeys(rest), - toolCalls: tool_calls ?? [], - ...(!context - ? {} - : { - context: { - ...(!context.messages - ? {} - : { - messages: context.messages.map(parseMessage), - }), - }, - }), - }; -} - -function parseError(error: ErrorModel): { error: ErrorModel } { - return { - error: { - ...error, - details: error["details"] ?? [], - }, - }; -} - -function parseContentFilterResultDetailsForPromptOutput({ - error, - ...rest -}: ContentFilterResultDetailsForPromptOutput = {}): ContentFilterResultDetailsForPrompt { - return error ? parseError(error) : camelCaseKeys(rest); -} - -function parseContentFilterResultsForChoiceOutput({ - error, - ...rest -}: ContentFilterResultsForChoiceOutput = {}): ContentFilterResultsForChoice { - return error ? parseError(error) : camelCaseKeys(rest); -} diff --git a/sdk/openai/openai/sources/customizations/api/client/openAIClient/index.ts b/sdk/openai/openai/sources/customizations/api/client/openAIClient/index.ts deleted file mode 100644 index dc5c1988e09b..000000000000 --- a/sdk/openai/openai/sources/customizations/api/client/openAIClient/index.ts +++ /dev/null @@ -1,400 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - ChatCompletionsOptions as GeneratedChatCompletionsOptions, - ImageGenerations, -} from "../../../../generated/src/models/models.js"; -import { GetChatCompletionsOptions, GetCompletionsOptions } from "../../../models/options.js"; -import { - _getCompletionsSend, - _getImageGenerationsDeserialize, - _getImageGenerationsSend, -} from "../../../../generated/src/api/client/openAIClient/index.js"; -import { getOaiSSEs } from "../../oaiSse.js"; -import { - AzureChatExtensionConfiguration, - OpenAIContext as Client, - GetChatCompletions200Response, - GetChatCompletionsDefaultResponse, - GetChatCompletionsWithAzureExtensions200Response, - GetChatCompletionsWithAzureExtensionsDefaultResponse, - GetCompletions200Response, - GetCompletionsDefaultResponse, - isUnexpected, - ChatCompletionsOptions as RestChatCompletionsOptions, - ChatRequestMessage as RestChatRequestMessage, -} from "../../../../generated/src/rest/index.js"; -import { StreamableMethod, operationOptionsToRequestParameters } from "@azure-rest/core-client"; -import { - ChatCompletions, - ChatRequestMessage, - Completions, - EventStream, -} from "../../../models/models.js"; -import { getChatCompletionsResult, getCompletionsResult } from "./deserializers.js"; -import { GetImagesOptions } from "../../../models/options.js"; -import { camelCaseKeys, snakeCaseKeys } from "../../util.js"; -import { - AudioResult, - AudioResultFormat, - AudioResultSimpleJson, - GetAudioTranscriptionOptions, - GetAudioTranslationOptions, -} from "../../../models/audio.js"; -import { createFile } from "@azure/core-rest-pipeline"; -import { ClientOpenAIClientGetChatCompletionsOptions } from "../../../../generated/src/models/options.js"; - -export async function _getChatCompletionsDeserialize( - result: GetChatCompletions200Response | GetChatCompletionsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body.error; - } - return getChatCompletionsResult(result.body); -} - -export async function _getCompletionsDeserialize( - result: GetCompletions200Response | GetCompletionsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body.error; - } - return getCompletionsResult(result.body); -} - -export function streamCompletions( - context: Client, - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = { requestOptions: {} }, -): Promise>> { - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const response = _getCompletionsSend( - context, - deploymentName, - { - prompt, - ...rest, - stream: true, - }, - { abortSignal, onResponse, requestOptions, tracingOptions }, - ); - return getOaiSSEs(response, getCompletionsResult); -} - -export async function getCompletions( - context: Client, - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = { requestOptions: {} }, -): Promise { - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const response = await _getCompletionsSend( - context, - deploymentName, - { - prompt, - ...rest, - }, - { abortSignal, onResponse, requestOptions, tracingOptions }, - ); - return _getCompletionsDeserialize(response); -} - -export async function getImages( - context: Client, - deploymentName: string, - prompt: string, - options: GetImagesOptions = { requestOptions: {} }, -): Promise { - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const result = await _getImageGenerationsSend( - context, - deploymentName, - { prompt, ...rest }, - { abortSignal, onResponse, requestOptions, tracingOptions }, - ); - return _getImageGenerationsDeserialize(result); -} - -function _getChatCompletionsSendX( - context: Client, - deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions & { stream?: boolean } = { requestOptions: {} }, -): StreamableMethod< - | GetChatCompletionsWithAzureExtensions200Response - | GetChatCompletionsWithAzureExtensionsDefaultResponse -> { - const { - azureExtensionOptions, - abortSignal, - onResponse, - requestOptions, - tracingOptions, - ...rest - } = options; - const coreOptions = { - abortSignal, - onResponse, - requestOptions, - tracingOptions, - }; - const azure = { - ...(!azureExtensionOptions?.extensions - ? {} - : { dataSources: azureExtensionOptions.extensions }), - ...(!azureExtensionOptions?.enhancements - ? {} - : { enhancements: azureExtensionOptions.enhancements }), - }; - return azure.dataSources || azure.enhancements - ? _getChatCompletionsWithAzureExtensionsSend( - context, - deploymentName, - { - messages, - ...rest, - ...azure, - }, - coreOptions, - ) - : _getChatCompletionsSend(context, deploymentName, { messages, ...rest }, coreOptions); -} - -export function streamChatCompletions( - context: Client, - deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, -): Promise> { - const response = _getChatCompletionsSendX(context, deploymentName, messages, { - ...options, - stream: true, - }); - return getOaiSSEs(response, getChatCompletionsResult); -} - -/** - * Gets chat completions for the provided chat messages. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export async function getChatCompletions( - context: Client, - deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, -): Promise { - const result = await _getChatCompletionsSendX(context, deploymentName, messages, options); - return _getChatCompletionsDeserialize(result); -} - -/** - * Returns the translation of an audio file. - * @param context - The context containing the client to use for this request. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. - * @param options - The options for this audio translation request. - * @returns The audio translation result. - */ -export async function getAudioTranslation( - context: Client, - deploymentName: string, - fileContent: Uint8Array, - options?: GetAudioTranslationOptions, -): Promise; -/** - * Returns the translation of an audio file. - * @param context - The context containing the client to use for this request. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. - * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. - * @param options - The options for this audio translation request. - * @returns The audio translation result. - */ -export async function getAudioTranslation( - context: Client, - deploymentName: string, - fileContent: Uint8Array, - format: Format, - options?: GetAudioTranslationOptions, -): Promise>; -// implementation -export async function getAudioTranslation( - context: Client, - deploymentName: string, - fileContent: Uint8Array, - formatOrOptions?: Format | GetAudioTranslationOptions, - inputOptions?: GetAudioTranslationOptions, -): Promise> { - const options = - inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); - const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const { body, status } = await context - .pathUnchecked("deployments/{deploymentName}/audio/translations", deploymentName) - .post({ - ...operationOptionsToRequestParameters({ - abortSignal, - onResponse, - tracingOptions, - requestOptions, - }), - contentType: "multipart/form-data", - body: { - ...snakeCaseKeys(rest), - file: createFile(fileContent, "placeholder.wav"), - ...(response_format ? { response_format } : {}), - }, - }); - if (status !== "200") { - throw body.error; - } - return response_format !== "verbose_json" - ? body - : (camelCaseKeys(body) as unknown as AudioResult); -} - -/** - * Returns the transcription of an audio file in a simple JSON format. - * @param context - The context containing the client to use for this request. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to transcribe. - * @param options - The options for this audio transcription request. - * @returns The audio transcription result in a simple JSON format. - */ -export async function getAudioTranscription( - context: Client, - deploymentName: string, - fileContent: Uint8Array, - options?: GetAudioTranscriptionOptions, -): Promise; -/** - * Returns the transcription of an audio file. - * @param context - The context containing the client to use for this request. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to transcribe. - * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. - * @param options - The options for this audio transcription request. - * @returns The audio transcription result in a format of your choice. - */ -export async function getAudioTranscription( - context: Client, - deploymentName: string, - fileContent: Uint8Array, - format: Format, - options?: GetAudioTranscriptionOptions, -): Promise>; -// implementation -export async function getAudioTranscription( - context: Client, - deploymentName: string, - fileContent: Uint8Array, - formatOrOptions?: Format | GetAudioTranscriptionOptions, - inputOptions?: GetAudioTranscriptionOptions, -): Promise> { - const options = - inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); - const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const { body, status } = await context - .pathUnchecked("deployments/{deploymentName}/audio/transcriptions", deploymentName) - .post({ - ...operationOptionsToRequestParameters({ - abortSignal, - onResponse, - tracingOptions, - requestOptions, - }), - contentType: "multipart/form-data", - body: { - ...snakeCaseKeys(rest), - file: createFile(fileContent, "placeholder.wav"), - ...(response_format ? { response_format } : {}), - }, - }); - if (status !== "200") { - throw body.error; - } - return response_format !== "verbose_json" - ? body - : (camelCaseKeys(body) as unknown as AudioResult); -} - -function _getChatCompletionsWithAzureExtensionsSend( - context: Client, - deploymentName: string, - body: GeneratedChatCompletionsOptions & { messages: ChatRequestMessage[] }, - options: ClientOpenAIClientGetChatCompletionsOptions = { requestOptions: {} }, -): StreamableMethod< - | GetChatCompletionsWithAzureExtensions200Response - | GetChatCompletionsWithAzureExtensionsDefaultResponse -> { - const { functions, functionCall, messages, dataSources, ...rest } = body; - return context - .path("/deployments/{deploymentId}/extensions/chat/completions", deploymentName) - .post({ - ...operationOptionsToRequestParameters(options), - body: { - ...snakeCaseKeys(rest), - dataSources: dataSources?.map( - ({ type, ...opts }) => ({ type, parameters: opts }) as AzureChatExtensionConfiguration, - ), - functions, - function_call: functionCall, - messages: messages.map(serializeChatRequestMessage), - } as RestChatCompletionsOptions, - }); -} - -function serializeChatRequestMessage(message: ChatRequestMessage): RestChatRequestMessage { - if (message.content === undefined) { - message.content = null; - } - switch (message.role) { - case "assistant": { - const { functionCall, toolCalls, ...rest } = message; - return { - ...snakeCaseKeys(rest), - ...(!toolCalls || toolCalls.length === 0 ? {} : { tool_calls: toolCalls }), - ...(functionCall ? { function_call: functionCall } : {}), - }; - } - default: { - return snakeCaseKeys(message); - } - } -} - -function _getChatCompletionsSend( - context: Client, - deploymentName: string, - body: GeneratedChatCompletionsOptions & { messages: ChatRequestMessage[] }, - options: ClientOpenAIClientGetChatCompletionsOptions = { requestOptions: {} }, -): StreamableMethod { - const { functions, functionCall, messages, ...rest } = body; - return context.path("/deployments/{deploymentId}/chat/completions", deploymentName).post({ - ...operationOptionsToRequestParameters(options), - body: { - ...snakeCaseKeys(rest), - functions, - function_call: functionCall, - messages: messages.map(serializeChatRequestMessage), - } as RestChatCompletionsOptions, - }); -} - -export async function _getChatCompletionsWithAzureExtensionsDeserialize(): Promise { - return {} as any; -} - -export async function getChatCompletionsWithAzureExtensions( - _context: unknown, - _deploymentId: unknown, - _body: unknown, - _options: unknown, -): Promise { - return {} as any; -} diff --git a/sdk/openai/openai/sources/customizations/api/getSSEs.browser.ts b/sdk/openai/openai/sources/customizations/api/getSSEs.browser.ts deleted file mode 100644 index b2733f49e2c7..000000000000 --- a/sdk/openai/openai/sources/customizations/api/getSSEs.browser.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { StreamableMethod } from "@azure-rest/core-client"; -import { wrapError } from "./util.js"; -import { streamToText } from "./readableStreamUtils.js"; - -export async function getStream( - response: StreamableMethod, -): Promise> { - const { body, status } = await response.asBrowserStream(); - if (status !== "200" && body !== undefined) { - const text = await streamToText(body); - throw wrapError(() => JSON.parse(text).error, "Error parsing response body"); - } - - if (!body) throw new Error("No stream found in response. Did you enable the stream option?"); - return body; -} diff --git a/sdk/openai/openai/sources/customizations/api/getSSEs.ts b/sdk/openai/openai/sources/customizations/api/getSSEs.ts deleted file mode 100644 index 637bde913444..000000000000 --- a/sdk/openai/openai/sources/customizations/api/getSSEs.ts +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { StreamableMethod } from "@azure-rest/core-client"; -import { RestError } from "@azure/core-rest-pipeline"; -import { wrapError } from "./util.js"; -import { IncomingMessage } from "http"; - -export async function getStream( - response: StreamableMethod, -): Promise { - const { body, status } = await response.asNodeStream(); - if (status !== "200" && body !== undefined) { - const text = await streamToText(body); - throw wrapError(() => JSON.parse(text).error, "Error parsing response body"); - } - - if (!body) throw new Error("No stream found in response. Did you enable the stream option?"); - return body as IncomingMessage; -} - -function streamToText(stream: NodeJS.ReadableStream): Promise { - return new Promise((resolve, reject) => { - const buffer: Buffer[] = []; - - stream.on("data", (chunk) => { - if (Buffer.isBuffer(chunk)) { - buffer.push(chunk); - } else { - buffer.push(Buffer.from(chunk)); - } - }); - stream.on("end", () => { - resolve(Buffer.concat(buffer).toString("utf8")); - }); - stream.on("error", (e) => { - if (e && e?.name === "AbortError") { - reject(e); - } else { - reject( - new RestError(`Error reading response as text: ${e.message}`, { - code: RestError.PARSE_ERROR, - }), - ); - } - }); - }); -} diff --git a/sdk/openai/openai/sources/customizations/api/index.ts b/sdk/openai/openai/sources/customizations/api/index.ts deleted file mode 100644 index 3ee94d7526d1..000000000000 --- a/sdk/openai/openai/sources/customizations/api/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -export { - getChatCompletions, - streamChatCompletions, - streamCompletions, - getAudioTranscription, - getAudioTranslation, - getImages, -} from "./client/openAIClient/index.js"; -export { - getEmbeddings, - getCompletions, -} from "../../generated/src/api/client/openAIClient/index.js"; -export { - createOpenAI, - OpenAIContext, - OpenAIClientOptions, -} from "../../generated/src/api/OpenAIContext.js"; diff --git a/sdk/openai/openai/sources/customizations/api/oaiSse.ts b/sdk/openai/openai/sources/customizations/api/oaiSse.ts deleted file mode 100644 index 4434f9ddbbd3..000000000000 --- a/sdk/openai/openai/sources/customizations/api/oaiSse.ts +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { StreamableMethod } from "@azure-rest/core-client"; -import { getStream } from "./getSSEs.js"; -import { wrapError } from "./util.js"; -import { EventStream } from "../models/models.js"; -import { EventMessage, createSseStream } from "@azure/core-sse"; -import { polyfillStream } from "./readableStreamUtils.js"; - -export async function getOaiSSEs>( - response: StreamableMethod, - toEvent: (obj: O) => TEvent, -): Promise> { - const stringStream = await getStream(response); - const eventStream = createSseStream(stringStream); - const jsonParser = new TransformStream({ - transform: async (chunk, controller) => { - if (chunk.data === "[DONE]") { - return; - } - controller.enqueue( - toEvent( - wrapError( - () => JSON.parse(chunk.data), - "Error parsing an event. See 'cause' for more details", - ), - ), - ); - }, - }); - /** TODO: remove these polyfills once all supported runtimes support them */ - return polyfillStream(eventStream.pipeThrough(jsonParser)); -} diff --git a/sdk/openai/openai/sources/customizations/api/policies/nonAzure.ts b/sdk/openai/openai/sources/customizations/api/policies/nonAzure.ts deleted file mode 100644 index 34944e9d0907..000000000000 --- a/sdk/openai/openai/sources/customizations/api/policies/nonAzure.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { PipelinePolicy } from "@azure/core-rest-pipeline"; - -export function nonAzurePolicy(): PipelinePolicy { - const policy: PipelinePolicy = { - name: "openAiEndpoint", - sendRequest: (request, next) => { - const obj = new URL(request.url); - const parts = obj.pathname.split("/"); - switch (parts[parts.length - 1]) { - case "completions": - if (parts[parts.length - 2] === "chat") { - obj.pathname = `${parts[1]}/chat/completions`; - } else { - obj.pathname = `${parts[1]}/completions`; - } - break; - case "embeddings": - obj.pathname = `${parts[1]}/embeddings`; - break; - case "generations": - if (parts[parts.length - 2] === "images") { - obj.pathname = `${parts[1]}/images/generations`; - } else { - throw new Error("Unexpected path"); - } - break; - case "transcriptions": - obj.pathname = `${parts[1]}/audio/transcriptions`; - break; - case "translations": - obj.pathname = `${parts[1]}/audio/translations`; - break; - } - obj.searchParams.delete("api-version"); - request.url = obj.toString(); - return next(request); - }, - }; - return policy; -} diff --git a/sdk/openai/openai/sources/customizations/api/readableStreamUtils.ts b/sdk/openai/openai/sources/customizations/api/readableStreamUtils.ts deleted file mode 100644 index d67982579af3..000000000000 --- a/sdk/openai/openai/sources/customizations/api/readableStreamUtils.ts +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -export function polyfillStream(stream: ReadableStream): ReadableStream & AsyncIterable { - makeAsyncIterable(stream); - return stream; -} - -function makeAsyncIterable( - webStream: any, -): asserts webStream is ReadableStream & AsyncIterable { - if (!webStream[Symbol.asyncIterator]) { - webStream[Symbol.asyncIterator] = () => toAsyncIterable(webStream); - } - - if (!webStream.values) { - webStream.values = () => toAsyncIterable(webStream); - } -} - -async function* toAsyncIterable(stream: ReadableStream): AsyncIterableIterator { - const reader = stream.getReader(); - try { - while (true) { - const { value, done } = await reader.read(); - if (done) { - return; - } - yield value; - } - } finally { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - } -} - -export async function streamToText(stream: ReadableStream): Promise { - const reader = stream.getReader(); - const buffers: Uint8Array[] = []; - let length = 0; - try { - // eslint-disable-next-line no-constant-condition - while (true) { - const { value, done } = await reader.read(); - if (done) { - return new TextDecoder().decode(concatBuffers(buffers, length)); - } - length += value.length; - buffers.push(value); - } - } finally { - reader.releaseLock(); - } -} - -function getBuffersLength(buffers: Uint8Array[]): number { - return buffers.reduce((acc, curr) => acc + curr.length, 0); -} - -function concatBuffers(buffers: Uint8Array[], len?: number): Uint8Array { - const length = len ?? getBuffersLength(buffers); - const res = new Uint8Array(length); - for (let i = 0, pos = 0; i < buffers.length; i++) { - const buffer = buffers[i]; - res.set(buffer, pos); - pos += buffer.length; - } - - return res; -} diff --git a/sdk/openai/openai/sources/customizations/api/util.ts b/sdk/openai/openai/sources/customizations/api/util.ts deleted file mode 100644 index 83155dc39b04..000000000000 --- a/sdk/openai/openai/sources/customizations/api/util.ts +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -type CamelCase = S extends `${infer P1}_${infer P2}` - ? `${Lowercase}${Capitalize>}` - : Lowercase; -type SnakeCase = S extends `${infer T}${infer U}` - ? `${T extends Capitalize ? "_" : ""}${Lowercase}${SnakeCase}` - : S; - -type MapCamelCaseKeysOverCollections = - T extends Array ? Array> : CamelCaseKeys; -type MapSnakeCaseKeysOverCollections = - T extends Array - ? Array> - : // : T extends (infer X | infer Y) - // ? MapSnakeCaseKeysOverCollections | MapSnakeCaseKeysOverCollections - SnakeCaseKeys; -type CamelCaseKeys = { - [K in keyof T as CamelCase]: MapCamelCaseKeysOverCollections; -}; -export type SnakeCaseKeys = { - [K in keyof T as SnakeCase]: MapSnakeCaseKeysOverCollections; -}; - -export function wrapError(f: () => T, message: string): T { - try { - const result = f(); - return result; - } catch (cause) { - throw new Error(`${message}: ${cause}`, { cause }); - } -} - -export function camelCaseKeys>(obj: O): CamelCaseKeys { - if (typeof obj !== "object" || !obj) return obj; - if (Array.isArray(obj)) { - return obj.map((v) => - camelCaseKeys ? (X extends Record ? X : never) : never>( - v, - ), - ) as CamelCaseKeys; - } else { - for (const key of Object.keys(obj)) { - const value = obj[key]; - const newKey = tocamelCase(key); - if (newKey !== key) { - delete obj[key]; - } - (obj[newKey] as Record) = - typeof obj[newKey] === "object" ? camelCaseKeys(value) : value; - } - return obj; - } -} - -export function snakeCaseKeys>(obj: O): SnakeCaseKeys { - if (typeof obj !== "object" || !obj) return obj; - if (Array.isArray(obj)) { - return obj.map((v) => - snakeCaseKeys ? (X extends Record ? X : never) : never>( - v, - ), - ) as SnakeCaseKeys; - } else { - for (const key of Object.keys(obj)) { - const value = obj[key]; - const newKey = toSnakeCase(key); - if (newKey !== key) { - delete obj[key]; - } - (obj[newKey] as Record) = - typeof obj[newKey] === "object" ? snakeCaseKeys(value) : value; - } - return obj; - } -} - -function tocamelCase

(str: P): CamelCase

{ - return str - .toLowerCase() - .replace(/([_][a-z])/g, (group) => group.toUpperCase().replace("_", "")) as CamelCase

; -} - -function toSnakeCase

(str: P): SnakeCase

{ - return str - .replace(/([A-Z])/g, (group) => `_${group.toLowerCase()}`) - .replace(/^_/, "") as SnakeCase

; -} diff --git a/sdk/openai/openai/sources/customizations/index.ts b/sdk/openai/openai/sources/customizations/index.ts deleted file mode 100644 index 50b116ea61cd..000000000000 --- a/sdk/openai/openai/sources/customizations/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -/** - * [Azure OpenAI](https://learn.microsoft.com/azure/cognitive-services/openai/overview) - * provides REST API access to OpenAI's powerful language models including the GPT-3, - * Codex and Embeddings model series. In addition, the new GPT-4 and ChatGPT (gpt-35-turbo) - * model series have now reached general availability. These models can be easily adapted - * to your specific task including but not limited to content generation, summarization, - * semantic search, and natural language to code translation. - * - * @packageDocumentation - */ - -export { AzureKeyCredential } from "@azure/core-auth"; -export { OpenAIClient } from "./OpenAIClient.js"; -export { OpenAIKeyCredential } from "./OpenAIKeyCredential.js"; -export * from "./models/audio.js"; diff --git a/sdk/openai/openai/sources/customizations/models/audio.ts b/sdk/openai/openai/sources/customizations/models/audio.ts deleted file mode 100644 index 256ce9125522..000000000000 --- a/sdk/openai/openai/sources/customizations/models/audio.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { OperationOptions } from "@azure-rest/core-client"; - -/** The result format of an audio task */ -export type AudioResultFormat = - /** This format will return an JSON structure containing a single \"text\" with the transcription. */ - | "json" - /** This format will return an JSON structure containing an enriched structure with the transcription. */ - | "verbose_json" - /** This will make the response return the transcription as plain/text. */ - | "text" - /** The transcription will be provided in SRT format (SubRip Text) in the form of plain/text. */ - | "srt" - /** The transcription will be provided in VTT format (Web Video Text Tracks) in the form of plain/text. */ - | "vtt"; - -/** Simple transcription response */ -export interface AudioResultSimpleJson { - /** Transcribed text. */ - text: string; -} - -/** Transcription response. */ -export interface AudioResultVerboseJson extends AudioResultSimpleJson { - /** Audio transcription task. */ - task: AudioTranscriptionTask; - /** Language detected in the source audio file. */ - language: string; - /** Duration. */ - duration: number; - /** Segments. */ - segments: AudioSegment[]; -} - -/** Audio transcription task type */ -/** "transcribe", "translate" */ -export type AudioTranscriptionTask = string; - -/** Transcription segment. */ -export interface AudioSegment { - /** Segment identifier. */ - id: number; - /** Segment start offset. */ - start: number; - /** Segment end offset. */ - end: number; - /** Segment text. */ - text: string; - /** Temperature. */ - temperature: number; - /** Average log probability. */ - avgLogprob: number; - /** Compression ratio. */ - compressionRatio: number; - /** Probability of 'no speech'. */ - noSpeechProb: number; - /** Tokens in this segment */ - tokens: number[]; - /** TODO */ - seek: number; -} - -/** The options for an audio transcription request */ -export interface GetAudioTranscriptionOptions extends OperationOptions { - /** An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language. */ - prompt?: string; - /** - * 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. - */ - temperature?: number; - /** The language of the input audio. Supplying the input language in ISO-639-1 format will improve accuracy and latency. */ - language?: string; -} - -/** The options for an audio translation request */ -export interface GetAudioTranslationOptions extends OperationOptions { - /** An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language. */ - prompt?: string; - /** - * 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. - */ - temperature?: number; -} - -/** The type of the result of the transcription based on the requested response format */ -export type AudioResult = { - json: AudioResultSimpleJson; - verbose_json: AudioResultVerboseJson; - vtt: string; - srt: string; - text: string; -}[ResponseFormat]; diff --git a/sdk/openai/openai/sources/customizations/models/models.ts b/sdk/openai/openai/sources/customizations/models/models.ts deleted file mode 100644 index 4381b9a33d23..000000000000 --- a/sdk/openai/openai/sources/customizations/models/models.ts +++ /dev/null @@ -1,875 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { ErrorModel } from "@azure-rest/core-client"; -import { - AzureChatEnhancementConfiguration, - AzureChatEnhancements, - AzureChatExtensionsMessageContext, - AzureCognitiveSearchIndexFieldMappingOptions, - AzureCosmosDBFieldMappingOptions, - ChatRole, - CompletionsFinishReason, - CompletionsLogProbabilityModel, - CompletionsUsage, - ContentFilterBlocklistIdResult, - ContentFilterCitedDetectionResult, - ContentFilterDetectionResult, - ContentFilterResult, - ElasticsearchIndexFieldMappingOptions, - FunctionCall, - PineconeFieldMappingOptions, -} from "../../generated/src/models/models.js"; - -/** The definition of a caller-specified function that chat completions may invoke in response to matching user input. */ -export interface FunctionDefinition { - /** The name of the function to be called. */ - name: string; - /** - * A description of what the function does. The model will use this description when selecting the function and - * interpreting its parameters. - */ - description?: string; - /** The parameters the functions accepts, described as a JSON Schema object. */ - parameters?: Record; -} - -/** - * The representation of a single prompt completion as part of an overall completions request. - * Generally, `n` choices are generated per provided prompt with a default value of 1. - * Token limits and other settings may limit the number of choices generated. - */ -export interface Choice { - /** The generated text for a given completions prompt. */ - text: string; - /** The ordered index associated with this completions choice. */ - index: number; - /** - * Information about the content filtering category (hate, sexual, violence, selfHarm), if it - * has been detected, as well as the severity level (very_low, low, medium, high-scale that - * determines the intensity and risk level of harmful content) and if it has been filtered or not. - */ - contentFilterResults?: ContentFilterResultsForChoice; - /** The log probabilities model for tokens associated with this completions choice. */ - logprobs: CompletionsLogProbabilityModel | null; - /** Reason for finishing */ - finishReason: CompletionsFinishReason | null; -} - -/** - * Representation of the response data from a completions request. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export interface Completions { - /** A unique identifier associated with this completions response. */ - id: string; - /** - * The first timestamp associated with generation activity for this completions response, - * represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. - */ - created: Date; - /** - * Content filtering results for zero or more prompts in the request. In a streaming request, - * results for different prompts may arrive at different times or in different orders. - */ - promptFilterResults: ContentFilterResultsForPrompt[]; - /** - * The collection of completions choices associated with this completions response. - * Generally, `n` choices are generated per provided prompt with a default value of 1. - * Token limits and other settings may limit the number of choices generated. - */ - choices: Choice[]; - /** Usage information for tokens processed and generated as part of this completions operation. */ - usage: CompletionsUsage; -} - -/** - * The representation of a single prompt completion as part of an overall chat completions request. - * Generally, `n` choices are generated per provided prompt with a default value of 1. - * Token limits and other settings may limit the number of choices generated. - */ -export interface ChatChoice { - /** The chat message for a given chat completions prompt. */ - message?: ChatResponseMessage; - /** The ordered index associated with this chat completions choice. */ - index: number; - /** The reason that this chat completions choice completed its generated. */ - finishReason: CompletionsFinishReason | null; - /** - * The reason the model stopped generating tokens, together with any applicable details. - * This structured representation replaces 'finishReason' for some models. - */ - finishDetails?: ChatFinishDetails; - /** The delta message content for a streaming response. */ - delta?: ChatResponseMessage; - /** - * Information about the content filtering category (hate, sexual, violence, selfHarm), if it - * has been detected, as well as the severity level (very_low, low, medium, high-scale that - * determines the intensity and risk level of harmful content) and if it has been filtered or not. - */ - contentFilterResults?: ContentFilterResultsForChoice; - /** - * Represents the output results of Azure OpenAI enhancements to chat completions, as configured via the matching input - * provided in the request. This supplementary information is only available when using Azure OpenAI and only when the - * request is configured to use enhancements. - */ - enhancements?: AzureChatEnhancements; -} - -/** Content filtering results for a single prompt in the request. */ -export interface ContentFilterResultsForPrompt { - /** The index of this prompt in the set of prompt results */ - promptIndex: number; - /** Content filtering results for this prompt */ - contentFilterResults: ContentFilterResultDetailsForPrompt; -} - -/** - * Representation of the response data from a chat completions request. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export interface ChatCompletions { - /** A unique identifier associated with this chat completions response. */ - id: string; - /** - * The first timestamp associated with generation activity for this completions response, - * represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. - */ - created: Date; - /** - * The collection of completions choices associated with this completions response. - * Generally, `n` choices are generated per provided prompt with a default value of 1. - * Token limits and other settings may limit the number of choices generated. - */ - choices: ChatChoice[]; - /** - * Content filtering results for zero or more prompts in the request. In a streaming request, - * results for different prompts may arrive at different times or in different orders. - */ - promptFilterResults: ContentFilterResultsForPrompt[]; - /** - * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that - * might impact determinism. - */ - systemFingerprint?: string; - /** Usage information for tokens processed and generated as part of this completions operation. */ - usage?: CompletionsUsage; -} - -/** Information about the content filtering category, if it has been detected. */ -export type ContentFilterResultDetailsForPrompt = - | ContentFilterSuccessResultDetailsForPrompt - | ContentFilterErrorResults; - -/** Information about the content filtering success result. */ -export interface ContentFilterSuccessResultDetailsForPrompt { - /** - * Describes language related to anatomical organs and genitals, romantic relationships, - * acts portrayed in erotic or affectionate terms, physical sexual acts, including - * those portrayed as an assault or a forced sexual violent act against one’s will, - * prostitution, pornography, and abuse. - */ - sexual?: ContentFilterResult; - /** - * Describes language related to physical actions intended to hurt, injure, damage, or - * kill someone or something; describes weapons, etc. - */ - violence?: ContentFilterResult; - /** - * Describes language attacks or uses that include pejorative or discriminatory language - * with reference to a person or identity group on the basis of certain differentiating - * attributes of these groups including but not limited to race, ethnicity, nationality, - * gender identity and expression, sexual orientation, religion, immigration status, ability - * status, personal appearance, and body size. - */ - hate?: ContentFilterResult; - /** - * Describes language related to physical actions intended to purposely hurt, injure, - * or damage one’s body, or kill oneself. - */ - selfHarm?: ContentFilterResult; - /** - * Describes an error returned if the content filtering system is - * down or otherwise unable to complete the operation in time. - */ - error?: undefined; - /** Describes whether profanity was detected. */ - profanity?: ContentFilterDetectionResult; - /** Describes detection results against configured custom blocklists. */ - customBlocklists?: ContentFilterBlocklistIdResult[]; - /** Whether a jailbreak attempt was detected in the prompt. */ - jailbreak?: ContentFilterDetectionResult; -} - -/** Information about the content filtering error result. */ -export interface ContentFilterErrorResults { - /** - * Describes an error returned if the content filtering system is - * down or otherwise unable to complete the operation in time. - */ - error: ErrorModel; -} - -/** Information about content filtering evaluated against generated model output. */ -export interface ContentFilterSuccessResultsForChoice { - /** - * Describes language related to anatomical organs and genitals, romantic relationships, - * acts portrayed in erotic or affectionate terms, physical sexual acts, including - * those portrayed as an assault or a forced sexual violent act against one’s will, - * prostitution, pornography, and abuse. - */ - sexual?: ContentFilterResult; - /** - * Describes language related to physical actions intended to hurt, injure, damage, or - * kill someone or something; describes weapons, etc. - */ - violence?: ContentFilterResult; - /** - * Describes language attacks or uses that include pejorative or discriminatory language - * with reference to a person or identity group on the basis of certain differentiating - * attributes of these groups including but not limited to race, ethnicity, nationality, - * gender identity and expression, sexual orientation, religion, immigration status, ability - * status, personal appearance, and body size. - */ - hate?: ContentFilterResult; - /** - * Describes language related to physical actions intended to purposely hurt, injure, - * or damage one’s body, or kill oneself. - */ - selfHarm?: ContentFilterResult; - /** Describes whether profanity was detected. */ - profanity?: ContentFilterDetectionResult; - /** Describes detection results against configured custom blocklists. */ - customBlocklists?: ContentFilterBlocklistIdResult[]; - /** - * Describes an error returned if the content filtering system is - * down or otherwise unable to complete the operation in time. - */ - error?: undefined; - /** Information about detection of protected text material. */ - protectedMaterialText?: ContentFilterDetectionResult; - /** Information about detection of protected code material. */ - protectedMaterialCode?: ContentFilterCitedDetectionResult; -} - -/** Information about the content filtering results, if it has been detected. */ -export type ContentFilterResultsForChoice = - | ContentFilterSuccessResultsForChoice - | ContentFilterErrorResults; - -/** A structured representation of a stop reason that signifies natural termination by the model. */ -export interface StopFinishDetails { - /** The object type, which is always 'stop' for this object. */ - type: "stop"; - /** The token sequence that the model terminated with. */ - stop: string; -} - -/** - * A structured representation of a stop reason that signifies a token limit was reached before the model could naturally - * complete. - */ -export interface MaxTokensFinishDetails { - /** The object type, which is always 'max_tokens' for this object. */ - type: "max_tokens"; -} - -/** - * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents - * a function invocation needed for a subsequent chat completions request to resolve. - */ -export interface ChatCompletionsFunctionToolCall { - /** The type of tool call, in this case always 'function'. */ - type: "function"; - /** The details of the function invocation requested by the tool call. */ - function: FunctionCall; - /** The ID of the tool call. */ - id: string; - /** The index of the tool call. */ - index?: number; -} - -/** - * A representation of a tool call that must be resolved in a subsequent request to perform the requested - * chat completion. - */ -export type ChatCompletionsToolCall = ChatCompletionsFunctionToolCall; - -/** Structured information about why a chat completions response terminated. */ -export type ChatFinishDetails = StopFinishDetails | MaxTokensFinishDetails; - -/** A representation of a chat message as received in a response. */ -export interface ChatResponseMessage { - /** The chat role associated with the message. */ - role: ChatRole; - /** The content of the message. */ - content: string | null; - /** - * The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat - * completions request to resolve as configured. - */ - toolCalls: ChatCompletionsToolCall[]; - /** - * The function call that must be resolved and have its output appended to subsequent input messages for the chat - * completions request to resolve as configured. - */ - functionCall?: FunctionCall; - /** - * If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those - * extensions while processing the chat completions request. - */ - context?: AzureChatExtensionsMessageContext; -} - -/** - * A request chat message containing system instructions that influence how the model will generate a chat completions - * response. - */ -export interface ChatRequestSystemMessage { - /** The chat role associated with this message, which is always 'system' for system messages. */ - role: "system"; - /** The contents of the system message. */ - content: string; - /** An optional name for the participant. */ - name?: string; -} - -/** A request chat message representing response or action from the assistant. */ -export interface ChatRequestAssistantMessage { - /** The chat role associated with this message, which is always 'assistant' for assistant messages. */ - role: "assistant"; - /** The content of the message. */ - content: string | null; - /** An optional name for the participant. */ - name?: string; - /** - * The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat - * completions request to resolve as configured. - */ - toolCalls?: Array; - /** - * The function call that must be resolved and have its output appended to subsequent input messages for the chat - * completions request to resolve as configured. - */ - functionCall?: FunctionCall; -} - -/** A request chat message representing user input to the assistant. */ -export interface ChatRequestUserMessage { - /** The chat role associated with this message, which is always 'user' for user messages. */ - role: "user"; - /** The contents of the user message, with available input types varying by selected model. */ - content: string | Array; - /** An optional name for the participant. */ - name?: string; -} - -/** A request chat message representing requested output from a configured tool. */ -export interface ChatRequestToolMessage { - /** The chat role associated with this message, which is always 'tool' for tool messages. */ - role: "tool"; - /** The content of the message. */ - content: string | null; - /** The ID of the tool call resolved by the provided content. */ - toolCallId: string; -} - -/** A request chat message representing requested output from a configured function. */ -export interface ChatRequestFunctionMessage { - /** The chat role associated with this message, which is always 'function' for function messages. */ - role: "function"; - /** The name of the function that was called to produce output. */ - name: string; - /** The output of the function as requested by the function call. */ - content: string | null; -} - -/** A representation of a chat message as provided in a request. */ -export type ChatRequestMessage = - | ChatRequestSystemMessage - | ChatRequestUserMessage - | ChatRequestAssistantMessage - | ChatRequestToolMessage - | ChatRequestFunctionMessage; - -/** A representation of an explicit, named tool selection to use for a chat completions request. */ -export type ChatCompletionsNamedToolSelection = ChatCompletionsNamedFunctionToolSelection; - -/** A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ -export interface ChatCompletionsNamedFunctionToolSelection { - /** The object type, which is always 'function'. */ - type: "function"; - /** Specifies a tool the model should use. Used to force the model to call a specific function. */ - function: { - /** The name of the function that should be called. */ - name: string; - }; -} - -/** - * Options for Azure OpenAI chat extensions. - */ -export interface AzureExtensionsOptions { - /** - * The configuration entries for Azure OpenAI chat extensions that use them. - * This additional specification is only compatible with Azure OpenAI. - */ - extensions?: AzureChatExtensionConfiguration[]; - /** If provided, the configuration options for available Azure OpenAI chat enhancements. */ - enhancements?: AzureChatEnhancementConfiguration; -} - -/** - * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat - * completions request that should use Azure OpenAI chat extensions to augment the response behavior. - * The use of this configuration is compatible only with Azure OpenAI. - */ -export type AzureChatExtensionConfiguration = - | AzureCognitiveSearchChatExtensionConfiguration - | AzureMachineLearningIndexChatExtensionConfiguration - | AzureCosmosDBChatExtensionConfiguration - | ElasticsearchChatExtensionConfiguration - | PineconeChatExtensionConfiguration; - -/** A representation of a tool that can be used by the model to improve a chat completions response. */ -export type ChatCompletionsToolDefinition = ChatCompletionsFunctionToolDefinition; - -/** The definition information for a chat completions function tool that can call a function in response to a tool call. */ -export interface ChatCompletionsFunctionToolDefinition { - /** The object name, which is always 'function'. */ - type: "function"; - /** The function definition details for the function tool. */ - function: FunctionDefinition; -} - -/** A representation of a structured content item within a chat message. */ -export type ChatMessageContentItem = ChatMessageTextContentItem | ChatMessageImageContentItem; - -/** A structured chat content item containing plain text. */ -export interface ChatMessageTextContentItem { - /** The discriminated object type: always 'text' for this type. */ - type: "text"; - /** The content of the message. */ - text: string; -} - -/** A structured chat content item containing an image reference. */ -export interface ChatMessageImageContentItem { - /** The discriminated object type: always 'image_url' for this type. */ - type: "image_url"; - /** An internet location, which must be accessible to the model,from which the image may be retrieved. */ - imageUrl: ChatMessageImageUrl; -} - -/** - * The collection of predefined behaviors for handling request-provided function information in a chat completions - * operation. - */ -/** "auto", "none" */ -export type FunctionCallPreset = "auto" | "none"; -/** The authentication types supported with Azure OpenAI On Your Data. */ -/** "APIKey", "ConnectionString", "KeyAndKeyId", "SystemAssignedManagedIdentity", "UserAssignedManagedIdentity" */ -export type OnYourDataAuthenticationType = - | "APIKey" - | "ConnectionString" - | "KeyAndKeyId" - | "SystemAssignedManagedIdentity" - | "UserAssignedManagedIdentity"; -/** The type of Azure Cognitive Search retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ -/** "simple", "semantic", "vector", "vectorSimpleHybrid", "vectorSemanticHybrid" */ -export type AzureCognitiveSearchQueryType = - | "simple" - | "semantic" - | "vector" - | "vectorSimpleHybrid" - | "vectorSemanticHybrid"; -/** - * Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with - * vector search. - */ -/** "Endpoint", "DeploymentName", "ModelId" */ -export type OnYourDataVectorizationSourceType = "Endpoint" | "DeploymentName" | "ModelId"; -/** The type of Elasticsearch® retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ -/** "simple", "vector" */ -export type ElasticsearchQueryType = "simple" | "vector"; -/** Represents a generic policy for how a chat completions tool may be selected. */ -/** "auto", "none" */ -export type ChatCompletionsToolSelectionPreset = "auto" | "none"; -/** The desired size of generated images. */ -/** "1024x1024", "1792x1024", "1024x1792" */ -export type ImageSize = "1024x1024" | "1792x1024" | "1024x1792"; -/** The format in which the generated images are returned. */ -/** "url", "b64_json" */ -export type ImageGenerationResponseFormat = "url" | "b64_json"; -/** - * An image generation configuration that specifies how the model should prioritize quality, cost, and speed. - * Only configurable with dall-e-3 models. - */ -/** "standard", "hd" */ -export type ImageGenerationQuality = "standard" | "hd"; -/** - * An image generation configuration that specifies how the model should incorporate realism and other visual characteristics. - * Only configurable with dall-e-3 models. - */ -/** "natural", "vivid" */ -export type ImageGenerationStyle = "natural" | "vivid"; - -/** The authentication options for Azure OpenAI On Your Data when using an API key. */ -export interface OnYourDataApiKeyAuthenticationOptions { - /** The authentication type of API key. */ - type: "APIKey"; - /** The API key to use for authentication. */ - key: string; -} - -/** The authentication options for Azure OpenAI On Your Data when using a connection string. */ -export interface OnYourDataConnectionStringAuthenticationOptions { - /** The authentication type of connection string. */ - type: "ConnectionString"; - /** The connection string to use for authentication. */ - connectionString: string; -} - -/** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. */ -export interface OnYourDataKeyAndKeyIdAuthenticationOptions { - /** The authentication type of Elasticsearch key and key ID pair. */ - type: "KeyAndKeyId"; - /** The key to use for authentication. */ - key: string; - /** The key ID to use for authentication. */ - keyId: string; -} - -/** The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. */ -export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions { - /** The authentication type of system-assigned managed identity. */ - type: "SystemAssignedManagedIdentity"; -} - -/** The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. */ -export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions { - /** The authentication type of user-assigned managed identity. */ - type: "UserAssignedManagedIdentity"; - /** The resource ID of the user-assigned managed identity to use for authentication. */ - managedIdentityResourceId: string; -} - -/** The authentication options for Azure OpenAI On Your Data. */ -export type OnYourDataAuthenticationOptions = - | OnYourDataApiKeyAuthenticationOptions - | OnYourDataConnectionStringAuthenticationOptions - | OnYourDataKeyAndKeyIdAuthenticationOptions - | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions - | OnYourDataUserAssignedManagedIdentityAuthenticationOptions; - -/** - * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based - * on a public Azure OpenAI endpoint call for embeddings. - */ -export interface OnYourDataEndpointVectorizationSource { - /** The type of vectorization source to use. Always 'Endpoint' for this type. */ - type: "Endpoint"; - /** Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. */ - endpoint: string; - /** Specifies the authentication options to use when retrieving embeddings from the specified endpoint. */ - authentication: OnYourDataAuthenticationOptions; -} - -/** - * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based - * on an internal embeddings model deployment name in the same Azure OpenAI resource. - */ -export interface OnYourDataDeploymentNameVectorizationSource { - /** The type of vectorization source to use. Always 'DeploymentName' for this type. */ - type: "DeploymentName"; - /** The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. */ - deploymentName: string; -} - -/** - * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based - * on a search service model ID. Currently only supported by Elasticsearch®. - */ -export interface OnYourDataModelIdVectorizationSource { - /** The type of vectorization source to use. Always 'ModelId' for this type. */ - type: "ModelId"; - /** The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. */ - modelId: string; -} - -/** A representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ -export type OnYourDataVectorizationSource = - | OnYourDataEndpointVectorizationSource - | OnYourDataDeploymentNameVectorizationSource - | OnYourDataModelIdVectorizationSource; - -/** - * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat - * extension. - */ -export interface PineconeChatExtensionConfiguration { - /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Pinecone. - */ - type: "Pinecone"; - /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. - */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The environment name of Pinecone. */ - environment: string; - /** The name of the Pinecone database index. */ - indexName: string; - /** Customized field mapping behavior to use when interacting with the search index. */ - fieldsMapping: PineconeFieldMappingOptions; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; -} - -/** - * A specific representation of configurable options for Azure Cognitive Search when using it as an Azure OpenAI chat - * extension. - */ -export interface AzureCognitiveSearchChatExtensionConfiguration { - /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Azure Cognitive Search. - */ - type: "AzureCognitiveSearch"; - /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. - */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The absolute endpoint path for the Azure Cognitive Search resource to use. */ - endpoint: string; - /** The name of the index to use as available in the referenced Azure Cognitive Search resource. */ - indexName: string; - /** The API key to use when interacting with the Azure Cognitive Search resource. */ - key?: string; - /** Customized field mapping behavior to use when interacting with the search index. */ - fieldsMapping?: AzureCognitiveSearchIndexFieldMappingOptions; - /** The query type to use with Azure Cognitive Search. */ - queryType?: AzureCognitiveSearchQueryType; - /** The additional semantic configuration for the query. */ - semanticConfiguration?: string; - /** Search filter. */ - filter?: string; - /** When using embeddings for search, specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of format `https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings?api-version={api-version}`. */ - embeddingEndpoint?: string; - /** When using embeddings, specifies the API key to use with the provided embeddings endpoint. */ - embeddingKey?: string; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; -} - -/** - * A specific representation of configurable options for Azure Machine Learning vector index when using it as an Azure - * OpenAI chat extension. - */ -export interface AzureMachineLearningIndexChatExtensionConfiguration { - /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Azure Machine Learning vector index. - */ - type: "AzureMLIndex"; - /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. - */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The resource ID of the Azure Machine Learning project. */ - projectResourceId: string; - /** The Azure Machine Learning vector index name. */ - name: string; - /** The version of the Azure Machine Learning vector index. */ - version: string; - /** Search filter. Only supported if the Azure Machine Learning vector index is of type AzureSearch. */ - filter?: string; -} - -/** - * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat - * extension. - */ -export interface AzureCosmosDBChatExtensionConfiguration { - /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Azure Cosmos DB. - */ - type: "AzureCosmosDB"; - /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. - */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The MongoDB vCore database name to use with Azure Cosmos DB. */ - databaseName: string; - /** The name of the Azure Cosmos DB resource container. */ - containerName: string; - /** The MongoDB vCore index name to use with Azure Cosmos DB. */ - indexName: string; - /** Customized field mapping behavior to use when interacting with the search index. */ - fieldsMapping: AzureCosmosDBFieldMappingOptions; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; -} - -/** - * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat - * extension. - */ -export interface ElasticsearchChatExtensionConfiguration { - /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Elasticsearch®. - */ - type: "Elasticsearch"; - /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. - */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The endpoint of Elasticsearch®. */ - endpoint: string; - /** The index name of Elasticsearch®. */ - indexName: string; - /** The index field mapping options of Elasticsearch®. */ - fieldsMapping?: ElasticsearchIndexFieldMappingOptions; - /** The query type of Elasticsearch®. */ - queryType?: ElasticsearchQueryType; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; -} - -/** - * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat - * extension. - */ -export interface PineconeChatExtensionConfiguration { - /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Pinecone. - */ - type: "Pinecone"; - /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. - */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The environment name of Pinecone. */ - environment: string; - /** The name of the Pinecone database index. */ - indexName: string; - /** Customized field mapping behavior to use when interacting with the search index. */ - fieldsMapping: PineconeFieldMappingOptions; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; -} -/** The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response -content that adheres to a specific schema. */ -export interface ChatCompletionsTextResponseFormat { - /** The object type, which is always 'text' for this object. */ - type: "text"; -} -/** A response format for Chat Completions that restricts responses to emitting valid JSON objects. - */ -export interface ChatCompletionsJsonResponseFormat { - /** The object type, which is always 'json_object' for this object. */ - type: "json_object"; -} - -/** The valid response formats Chat Completions can provide. Used to enable JSON mode. */ -export type ChatCompletionsResponseFormat = - | ChatCompletionsTextResponseFormat - | ChatCompletionsJsonResponseFormat; - -/** A representation of the possible image detail levels for image-based chat completions message content. */ -/** "auto", "low", "high" */ -export type ChatMessageImageDetailLevel = "auto" | "low" | "high"; - -/** An internet location from which the model may retrieve an image. */ -export interface ChatMessageImageUrl { - /** The URL of the image. */ - url: string; - /** - * The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and - * accuracy. - * - * Possible values: auto, low, high - */ - detail?: ChatMessageImageDetailLevel; -} - -/** A readable stream that is iterable and disposable. */ -export interface EventStream extends ReadableStream, AsyncIterable {} diff --git a/sdk/openai/openai/sources/customizations/models/options.ts b/sdk/openai/openai/sources/customizations/models/options.ts deleted file mode 100644 index c3b56dc45889..000000000000 --- a/sdk/openai/openai/sources/customizations/models/options.ts +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { OperationOptions } from "@azure-rest/core-client"; -import { - ImageSize, - ImageGenerationResponseFormat, - ImageGenerationQuality, - ImageGenerationStyle, - ChatCompletionsNamedToolSelection, - ChatCompletionsToolDefinition, - ChatCompletionsResponseFormat, - FunctionCallPreset, - FunctionName, -} from "../../generated/src/models/models.js"; -import { AzureExtensionsOptions, FunctionDefinition } from "./models.js"; - -/** Represents the request data used to generate images. */ -export interface GetImagesOptions extends OperationOptions { - /** - * The number of images to generate. - * Dall-e-3 models only support a value of 1. - */ - n?: number; - /** - * The desired dimensions for generated images. - * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. - */ - size?: ImageSize; - /** The format in which image generation response items should be presented. */ - responseFormat?: ImageGenerationResponseFormat; - /** - * The desired image generation quality level to use. - */ - quality?: ImageGenerationQuality; - /** - * The desired image generation style to use. - */ - style?: ImageGenerationStyle; - /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ - user?: string; -} - -/** Options for to custom embeddings request */ -export interface GetEmbeddingsOptions extends OperationOptions { - /** - * An identifier for the caller or end user of the operation. This may be used for tracking - * or rate-limiting purposes. - */ - user?: string; - /** - * The model name to provide as part of this embeddings request. - * Not applicable to Azure OpenAI, where deployment information should be included in the Azure - * resource URI that's connected to. - */ - model?: string; -} - -/** - * The configuration information for a completions request. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export interface GetCompletionsOptions extends OperationOptions { - /** The maximum number of tokens to generate. */ - maxTokens?: number; - /** - * The sampling temperature to use that controls the apparent creativity of generated completions. - * Higher values will make output more random while lower values will make results more focused - * and deterministic. - * It is not recommended to modify temperature and top_p for the same completions request as the - * interaction of these two settings is difficult to predict. - */ - temperature?: number; - /** - * An alternative to sampling with temperature called nucleus sampling. This value causes the - * model to consider the results of tokens with the provided probability mass. As an example, a - * value of 0.15 will cause only the tokens comprising the top 15% of probability mass to be - * considered. - * It is not recommended to modify temperature and top_p for the same completions request as the - * interaction of these two settings is difficult to predict. - */ - topP?: number; - /** - * A map between GPT token IDs and bias scores that influences the probability of specific tokens - * appearing in a completions response. Token IDs are computed via external tokenizer tools, while - * bias scores reside in the range of -100 to 100 with minimum and maximum values corresponding to - * a full ban or exclusive selection of a token, respectively. The exact behavior of a given bias - * score varies by model. - */ - logitBias?: Record; - /** - * An identifier for the caller or end user of the operation. This may be used for tracking - * or rate-limiting purposes. - */ - user?: string; - /** - * The number of completions choices that should be generated per provided prompt as part of an - * overall completions response. - * Because this setting can generate many completions, it may quickly consume your token quota. - * Use carefully and ensure reasonable settings for max_tokens and stop. - */ - n?: number; - /** - * A value that controls the emission of log probabilities for the provided number of most likely - * tokens within a completions response. - */ - logprobs?: number; - /** - * A value specifying whether completions responses should include input prompts as prefixes to - * their generated output. - */ - echo?: boolean; - /** A collection of textual sequences that will end completions generation. */ - stop?: string[]; - /** - * A value that influences the probability of generated tokens appearing based on their existing - * presence in generated text. - * Positive values will make tokens less likely to appear when they already exist and increase the - * model's likelihood to output new topics. - */ - presencePenalty?: number; - /** - * A value that influences the probability of generated tokens appearing based on their cumulative - * frequency in generated text. - * Positive values will make tokens less likely to appear as their frequency increases and - * decrease the likelihood of the model repeating the same statements verbatim. - */ - frequencyPenalty?: number; - /** - * A value that controls how many completions will be internally generated prior to response - * formulation. - * When used together with n, best_of controls the number of candidate completions and must be - * greater than n. - * Because this setting can generate many completions, it may quickly consume your token quota. - * Use carefully and ensure reasonable settings for max_tokens and stop. - */ - bestOf?: number; -} - -/** - * This module contains models that we want to live side-by-side with the - * corresponding generated models. This is useful for providing customer-facing - * models that have different names/types than the generated models. - */ - -export interface GetChatCompletionsOptions extends OperationOptions { - /** A list of functions the model may generate JSON inputs for. */ - functions?: FunctionDefinition[]; - /** - * Controls how the model responds to function calls. "none" means the model does not call a function, - * and responds to the end-user. "auto" means the model can pick between an end-user or calling a function. - * Specifying a particular function via `{"name": "my_function"}` forces the model to call that function. - * "none" is the default when no functions are present. "auto" is the default if functions are present. - */ - functionCall?: FunctionCallPreset | FunctionName; - /** The maximum number of tokens to generate. */ - maxTokens?: number; - /** - * The sampling temperature to use that controls the apparent creativity of generated completions. - * Higher values will make output more random while lower values will make results more focused - * and deterministic. - * It is not recommended to modify temperature and topP for the same completions request as the - * interaction of these two settings is difficult to predict. - */ - temperature?: number; - /** - * An alternative to sampling with temperature called nucleus sampling. This value causes the - * model to consider the results of tokens with the provided probability mass. As an example, a - * value of 0.15 will cause only the tokens comprising the top 15% of probability mass to be - * considered. - * It is not recommended to modify temperature and topP for the same completions request as the - * interaction of these two settings is difficult to predict. - */ - topP?: number; - /** - * A map between GPT token IDs and bias scores that influences the probability of specific tokens - * appearing in a completions response. Token IDs are computed via external tokenizer tools, while - * bias scores reside in the range of -100 to 100 with minimum and maximum values corresponding to - * a full ban or exclusive selection of a token, respectively. The exact behavior of a given bias - * score varies by model. - */ - logitBias?: Record; - /** - * An identifier for the caller or end user of the operation. This may be used for tracking - * or rate-limiting purposes. - */ - user?: string; - /** - * The number of chat completions choices that should be generated for a chat completions - * response. - * Because this setting can generate many completions, it may quickly consume your token quota. - * Use carefully and ensure reasonable settings for maxTokens and stop. - */ - n?: number; - /** A collection of textual sequences that will end completions generation. */ - stop?: string[]; - /** - * A value that influences the probability of generated tokens appearing based on their existing - * presence in generated text. - * Positive values will make tokens less likely to appear when they already exist and increase the - * model's likelihood to output new topics. - */ - presencePenalty?: number; - /** - * A value that influences the probability of generated tokens appearing based on their cumulative - * frequency in generated text. - * Positive values will make tokens less likely to appear as their frequency increases and - * decrease the likelihood of the model repeating the same statements verbatim. - */ - frequencyPenalty?: number; - /** - * If specified, the system will make a best effort to sample deterministically such that repeated requests with the - * same seed and parameters should return the same result. Determinism is not guaranteed, and you should refer to the - * system_fingerprint response parameter to monitor changes in the backend." - */ - seed?: number; - /** An object specifying the format that the model must output. Used to enable JSON mode. */ - responseFormat?: ChatCompletionsResponseFormat; - /** The available tool definitions that the chat completions request can use, including caller-defined functions. */ - tools?: ChatCompletionsToolDefinition[]; - /** If specified, the model will configure which of the provided tools it can use for the chat completions response. */ - toolChoice?: ChatCompletionsNamedToolSelection; - /** - * The configuration entries for Azure OpenAI chat extensions that use them. - * This additional specification is only compatible with Azure OpenAI. - */ - azureExtensionOptions?: AzureExtensionsOptions; -} diff --git a/sdk/openai/openai/sources/generated/src/OpenAIClient.ts b/sdk/openai/openai/sources/generated/src/OpenAIClient.ts deleted file mode 100644 index c54fa20754b8..000000000000 --- a/sdk/openai/openai/sources/generated/src/OpenAIClient.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { TokenCredential, KeyCredential } from "@azure/core-auth"; -import { Pipeline } from "@azure/core-rest-pipeline"; -import { - getClientOperations, - ClientOperations, -} from "./classic/client/index.js"; -import { - createOpenAI, - OpenAIClientOptions, - OpenAIContext, -} from "./api/index.js"; - -export { OpenAIClientOptions } from "./api/OpenAIContext.js"; - -export class OpenAIClient { - private _client: OpenAIContext; - /** The pipeline used by this client to make requests */ - public readonly pipeline: Pipeline; - - constructor( - endpoint: string, - credential: KeyCredential | TokenCredential, - options: OpenAIClientOptions = {} - ) { - this._client = createOpenAI(endpoint, credential, options); - this.pipeline = this._client.pipeline; - this.client = getClientOperations(this._client); - } - - /** The operation groups for ClientOpenAIClient */ - public readonly client: ClientOperations; -} diff --git a/sdk/openai/openai/sources/generated/src/api/client/openAIClient/index.ts b/sdk/openai/openai/sources/generated/src/api/client/openAIClient/index.ts deleted file mode 100644 index 667571adc1a0..000000000000 --- a/sdk/openai/openai/sources/generated/src/api/client/openAIClient/index.ts +++ /dev/null @@ -1,1233 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { - AudioTranscriptionOptions, - AudioTranscription, - AudioTranslationOptions, - AudioTranslation, - CompletionsOptions, - Completions, - ChatCompletionsOptions, - ChatCompletions, - ImageGenerationOptions, - ImageGenerations, - EmbeddingsOptions, - Embeddings, -} from "../../../models/models.js"; -import { - GetAudioTranscriptionAsPlainText200Response, - GetAudioTranscriptionAsPlainTextDefaultResponse, - GetAudioTranscriptionAsResponseObject200Response, - GetAudioTranscriptionAsResponseObjectDefaultResponse, - GetAudioTranslationAsPlainText200Response, - GetAudioTranslationAsPlainTextDefaultResponse, - GetAudioTranslationAsResponseObject200Response, - GetAudioTranslationAsResponseObjectDefaultResponse, - GetChatCompletions200Response, - GetChatCompletionsDefaultResponse, - GetChatCompletionsWithAzureExtensions200Response, - GetChatCompletionsWithAzureExtensionsDefaultResponse, - GetCompletions200Response, - GetCompletionsDefaultResponse, - GetEmbeddings200Response, - GetEmbeddingsDefaultResponse, - GetImageGenerations200Response, - GetImageGenerationsDefaultResponse, - isUnexpected, - OpenAIContext as Client, -} from "../../../rest/index.js"; -import { - StreamableMethod, - operationOptionsToRequestParameters, -} from "@azure-rest/core-client"; -import { uint8ArrayToString } from "@azure/core-util"; -import { - ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ClientOpenAIClientGetCompletionsOptions, - ClientOpenAIClientGetChatCompletionsOptions, - ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ClientOpenAIClientGetImageGenerationsOptions, - ClientOpenAIClientGetEmbeddingsOptions, -} from "../../../models/options.js"; - -export function _getAudioTranscriptionAsPlainTextSend( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions = { - requestOptions: {}, - } -): StreamableMethod< - | GetAudioTranscriptionAsPlainText200Response - | GetAudioTranscriptionAsPlainTextDefaultResponse -> { - return context - .path("/deployments/{deploymentId}/audio/transcriptions", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - language: body["language"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - | GetAudioTranscriptionAsPlainText200Response - | GetAudioTranscriptionAsPlainTextDefaultResponse - >; -} - -export async function _getAudioTranscriptionAsPlainTextDeserialize( - result: - | GetAudioTranscriptionAsPlainText200Response - | GetAudioTranscriptionAsPlainTextDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return result.body; -} - -/** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. - */ -export async function getAudioTranscriptionAsPlainText( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions = { - requestOptions: {}, - } -): Promise { - const result = await _getAudioTranscriptionAsPlainTextSend( - context, - deploymentId, - body, - options - ); - return _getAudioTranscriptionAsPlainTextDeserialize(result); -} - -export function _getAudioTranscriptionAsResponseObjectSend( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions = { - requestOptions: {}, - } -): StreamableMethod< - | GetAudioTranscriptionAsResponseObject200Response - | GetAudioTranscriptionAsResponseObjectDefaultResponse -> { - return context - .path("/deployments/{deploymentId}/audio/transcriptions", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - language: body["language"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - | GetAudioTranscriptionAsResponseObject200Response - | GetAudioTranscriptionAsResponseObjectDefaultResponse - >; -} - -export async function _getAudioTranscriptionAsResponseObjectDeserialize( - result: - | GetAudioTranscriptionAsResponseObject200Response - | GetAudioTranscriptionAsResponseObjectDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - text: result.body["text"], - task: result.body["task"], - language: result.body["language"], - duration: result.body["duration"], - segments: !result.body["segments"] - ? result.body["segments"] - : result.body["segments"].map((p) => ({ - id: p["id"], - start: p["start"], - end: p["end"], - text: p["text"], - temperature: p["temperature"], - avgLogprob: p["avg_logprob"], - compressionRatio: p["compression_ratio"], - noSpeechProb: p["no_speech_prob"], - tokens: p["tokens"], - seek: p["seek"], - })), - }; -} - -/** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. - */ -export async function getAudioTranscriptionAsResponseObject( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions = { - requestOptions: {}, - } -): Promise { - const result = await _getAudioTranscriptionAsResponseObjectSend( - context, - deploymentId, - body, - options - ); - return _getAudioTranscriptionAsResponseObjectDeserialize(result); -} - -export function _getAudioTranslationAsPlainTextSend( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions = { - requestOptions: {}, - } -): StreamableMethod< - | GetAudioTranslationAsPlainText200Response - | GetAudioTranslationAsPlainTextDefaultResponse -> { - return context - .path("/deployments/{deploymentId}/audio/translations", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - | GetAudioTranslationAsPlainText200Response - | GetAudioTranslationAsPlainTextDefaultResponse - >; -} - -export async function _getAudioTranslationAsPlainTextDeserialize( - result: - | GetAudioTranslationAsPlainText200Response - | GetAudioTranslationAsPlainTextDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return result.body; -} - -/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ -export async function getAudioTranslationAsPlainText( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions = { - requestOptions: {}, - } -): Promise { - const result = await _getAudioTranslationAsPlainTextSend( - context, - deploymentId, - body, - options - ); - return _getAudioTranslationAsPlainTextDeserialize(result); -} - -export function _getAudioTranslationAsResponseObjectSend( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions = { - requestOptions: {}, - } -): StreamableMethod< - | GetAudioTranslationAsResponseObject200Response - | GetAudioTranslationAsResponseObjectDefaultResponse -> { - return context - .path("/deployments/{deploymentId}/audio/translations", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - | GetAudioTranslationAsResponseObject200Response - | GetAudioTranslationAsResponseObjectDefaultResponse - >; -} - -export async function _getAudioTranslationAsResponseObjectDeserialize( - result: - | GetAudioTranslationAsResponseObject200Response - | GetAudioTranslationAsResponseObjectDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - text: result.body["text"], - task: result.body["task"], - language: result.body["language"], - duration: result.body["duration"], - segments: !result.body["segments"] - ? result.body["segments"] - : result.body["segments"].map((p) => ({ - id: p["id"], - start: p["start"], - end: p["end"], - text: p["text"], - temperature: p["temperature"], - avgLogprob: p["avg_logprob"], - compressionRatio: p["compression_ratio"], - noSpeechProb: p["no_speech_prob"], - tokens: p["tokens"], - seek: p["seek"], - })), - }; -} - -/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ -export async function getAudioTranslationAsResponseObject( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions = { - requestOptions: {}, - } -): Promise { - const result = await _getAudioTranslationAsResponseObjectSend( - context, - deploymentId, - body, - options - ); - return _getAudioTranslationAsResponseObjectDeserialize(result); -} - -export function _getCompletionsSend( - context: Client, - deploymentId: string, - body: CompletionsOptions, - options: ClientOpenAIClientGetCompletionsOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/deployments/{deploymentId}/completions", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - body: { - prompt: body["prompt"], - max_tokens: body["maxTokens"], - temperature: body["temperature"], - top_p: body["topP"], - logit_bias: body["logitBias"], - user: body["user"], - n: body["n"], - logprobs: body["logprobs"], - echo: body["echo"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - best_of: body["bestOf"], - stream: body["stream"], - model: body["model"], - }, - }); -} - -export async function _getCompletionsDeserialize( - result: GetCompletions200Response | GetCompletionsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - id: result.body["id"], - created: new Date(result.body["created"]), - promptFilterResults: !result.body["prompt_filter_results"] - ? result.body["prompt_filter_results"] - : result.body["prompt_filter_results"].map((p) => ({ - promptIndex: p["prompt_index"], - contentFilterResults - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - severity: p.content_filter_results?.sexual?.["severity"], - filtered: p.content_filter_results?.sexual?.["filtered"], - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - severity: - p.content_filter_results?.violence?.["severity"], - filtered: - p.content_filter_results?.violence?.["filtered"], - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - severity: p.content_filter_results?.hate?.["severity"], - filtered: p.content_filter_results?.hate?.["filtered"], - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - severity: - p.content_filter_results?.self_harm?.["severity"], - filtered: - p.content_filter_results?.self_harm?.["filtered"], - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: - p.content_filter_results?.profanity?.["filtered"], - detected: - p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.[ - "custom_blocklists" - ] - ? p.content_filter_results?.["custom_blocklists"] - : p.content_filter_results?.["custom_blocklists"].map( - (p) => ({ id: p["id"], filtered: p["filtered"] }) - ), - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - jailbreak: !p.content_filter_results?.jailbreak - ? undefined - : { - filtered: - p.content_filter_results?.jailbreak?.["filtered"], - detected: - p.content_filter_results?.jailbreak?.["detected"], - }, - }, - })), - choices: result.body["choices"].map((p) => ({ - text: p["text"], - index: p["index"], - contentFilterResults: !p.content_filter_results - ? undefined - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - severity: p.content_filter_results?.sexual?.["severity"], - filtered: p.content_filter_results?.sexual?.["filtered"], - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - severity: p.content_filter_results?.violence?.["severity"], - filtered: p.content_filter_results?.violence?.["filtered"], - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - severity: p.content_filter_results?.hate?.["severity"], - filtered: p.content_filter_results?.hate?.["filtered"], - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - severity: p.content_filter_results?.self_harm?.["severity"], - filtered: p.content_filter_results?.self_harm?.["filtered"], - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: p.content_filter_results?.profanity?.["filtered"], - detected: p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.["custom_blocklists"] - ? p.content_filter_results?.["custom_blocklists"] - : p.content_filter_results?.["custom_blocklists"].map((p) => ({ - id: p["id"], - filtered: p["filtered"], - })), - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - protectedMaterialText: !p.content_filter_results - ?.protected_material_text - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_text?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_text?.[ - "detected" - ], - }, - protectedMaterialCode: !p.content_filter_results - ?.protected_material_code - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_code?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_code?.[ - "detected" - ], - url: p.content_filter_results?.protected_material_code?.[ - "URL" - ], - license: - p.content_filter_results?.protected_material_code?.[ - "license" - ], - }, - }, - logprobs: - p.logprobs === null - ? null - : { - tokens: p.logprobs["tokens"], - tokenLogprobs: p.logprobs["token_logprobs"], - topLogprobs: p.logprobs["top_logprobs"], - textOffset: p.logprobs["text_offset"], - }, - finishReason: p["finish_reason"], - })), - usage: { - completionTokens: result.body.usage["completion_tokens"], - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; -} - -/** - * Gets completions for the provided input prompts. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export async function getCompletions( - context: Client, - deploymentId: string, - body: CompletionsOptions, - options: ClientOpenAIClientGetCompletionsOptions = { requestOptions: {} } -): Promise { - const result = await _getCompletionsSend( - context, - deploymentId, - body, - options - ); - return _getCompletionsDeserialize(result); -} - -export function _getChatCompletionsSend( - context: Client, - deploymentId: string, - body: ChatCompletionsOptions, - options: ClientOpenAIClientGetChatCompletionsOptions = { requestOptions: {} } -): StreamableMethod< - GetChatCompletions200Response | GetChatCompletionsDefaultResponse -> { - return context - .path("/deployments/{deploymentId}/chat/completions", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - body: { - messages: body["messages"].map((p) => ({ role: p["role"] })), - functions: !body["functions"] - ? body["functions"] - : body["functions"].map((p) => ({ - name: p["name"], - description: p["description"], - parameters: p["parameters"], - })), - function_call: body["functionCall"], - max_tokens: body["maxTokens"], - temperature: body["temperature"], - top_p: body["topP"], - logit_bias: body["logitBias"], - user: body["user"], - n: body["n"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - stream: body["stream"], - model: body["model"], - dataSources: !body["dataSources"] - ? body["dataSources"] - : body["dataSources"].map((p) => ({ type: p["type"] })), - enhancements: !body.enhancements - ? undefined - : { - grounding: !body.enhancements?.grounding - ? undefined - : { enabled: body.enhancements?.grounding?.["enabled"] }, - ocr: !body.enhancements?.ocr - ? undefined - : { enabled: body.enhancements?.ocr?.["enabled"] }, - }, - seed: body["seed"], - response_format: body["responseFormat"], - tools: !body["tools"] - ? body["tools"] - : body["tools"].map((p) => ({ type: p["type"] })), - tool_choice: body["toolChoice"], - } as any, - }); -} - -export async function _getChatCompletionsDeserialize( - result: GetChatCompletions200Response | GetChatCompletionsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - id: result.body["id"], - created: new Date(result.body["created"]), - choices: result.body["choices"].map((p) => ({ - message: !p.message ? undefined : (p.message as any), - index: p["index"], - finishReason: p["finish_reason"], - finishDetails: !p.finish_details - ? undefined - : { type: p.finish_details?.["type"] }, - delta: !p.delta - ? undefined - : { - role: p.delta?.["role"], - content: p.delta?.["content"], - toolCalls: !p.delta?.["tool_calls"] - ? p.delta?.["tool_calls"] - : p.delta?.["tool_calls"].map((p) => ({ - type: p["type"], - id: p["id"], - })), - functionCall: !p.delta?.function_call - ? undefined - : { - name: p.delta?.function_call?.["name"], - arguments: p.delta?.function_call?.["arguments"], - }, - context: !p.delta?.context - ? undefined - : { - messages: !p.delta?.context?.messages - ? undefined - : (p.delta?.context?.messages as any), - }, - }, - contentFilterResults: !p.content_filter_results - ? undefined - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - severity: p.content_filter_results?.sexual?.["severity"], - filtered: p.content_filter_results?.sexual?.["filtered"], - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - severity: p.content_filter_results?.violence?.["severity"], - filtered: p.content_filter_results?.violence?.["filtered"], - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - severity: p.content_filter_results?.hate?.["severity"], - filtered: p.content_filter_results?.hate?.["filtered"], - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - severity: p.content_filter_results?.self_harm?.["severity"], - filtered: p.content_filter_results?.self_harm?.["filtered"], - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: p.content_filter_results?.profanity?.["filtered"], - detected: p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.["custom_blocklists"] - ? p.content_filter_results?.["custom_blocklists"] - : p.content_filter_results?.["custom_blocklists"].map((p) => ({ - id: p["id"], - filtered: p["filtered"], - })), - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - protectedMaterialText: !p.content_filter_results - ?.protected_material_text - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_text?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_text?.[ - "detected" - ], - }, - protectedMaterialCode: !p.content_filter_results - ?.protected_material_code - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_code?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_code?.[ - "detected" - ], - url: p.content_filter_results?.protected_material_code?.[ - "URL" - ], - license: - p.content_filter_results?.protected_material_code?.[ - "license" - ], - }, - }, - enhancements: { - grounding: !p.enhancements?.grounding - ? undefined - : { - lines: p.enhancements.grounding?.["lines"].map((p) => ({ - text: p["text"], - spans: p["spans"].map((p) => ({ - text: p["text"], - offset: p["offset"], - length: p["length"], - polygon: p["polygon"].map((p) => ({ x: p["x"], y: p["y"] })), - })), - })), - }, - }, - })), - promptFilterResults: !result.body["prompt_filter_results"] - ? result.body["prompt_filter_results"] - : result.body["prompt_filter_results"].map((p) => ({ - promptIndex: p["prompt_index"], - contentFilterResults - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - severity: p.content_filter_results?.sexual?.["severity"], - filtered: p.content_filter_results?.sexual?.["filtered"], - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - severity: - p.content_filter_results?.violence?.["severity"], - filtered: - p.content_filter_results?.violence?.["filtered"], - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - severity: p.content_filter_results?.hate?.["severity"], - filtered: p.content_filter_results?.hate?.["filtered"], - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - severity: - p.content_filter_results?.self_harm?.["severity"], - filtered: - p.content_filter_results?.self_harm?.["filtered"], - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: - p.content_filter_results?.profanity?.["filtered"], - detected: - p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.[ - "custom_blocklists" - ] - ? p.content_filter_results?.["custom_blocklists"] - : p.content_filter_results?.["custom_blocklists"].map( - (p) => ({ id: p["id"], filtered: p["filtered"] }) - ), - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - jailbreak: !p.content_filter_results?.jailbreak - ? undefined - : { - filtered: - p.content_filter_results?.jailbreak?.["filtered"], - detected: - p.content_filter_results?.jailbreak?.["detected"], - }, - }, - })), - systemFingerprint: result.body["system_fingerprint"], - usage: { - completionTokens: result.body.usage["completion_tokens"], - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; -} - -/** - * Gets chat completions for the provided chat messages. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export async function getChatCompletions( - context: Client, - deploymentId: string, - body: ChatCompletionsOptions, - options: ClientOpenAIClientGetChatCompletionsOptions = { requestOptions: {} } -): Promise { - const result = await _getChatCompletionsSend( - context, - deploymentId, - body, - options - ); - return _getChatCompletionsDeserialize(result); -} - -export function _getChatCompletionsWithAzureExtensionsSend( - context: Client, - deploymentId: string, - body: ChatCompletionsOptions, - options: ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions = { - requestOptions: {}, - } -): StreamableMethod< - | GetChatCompletionsWithAzureExtensions200Response - | GetChatCompletionsWithAzureExtensionsDefaultResponse -> { - return context - .path( - "/deployments/{deploymentId}/extensions/chat/completions", - deploymentId - ) - .post({ - ...operationOptionsToRequestParameters(options), - body: { - messages: body["messages"].map((p) => ({ role: p["role"] })), - functions: !body["functions"] - ? body["functions"] - : body["functions"].map((p) => ({ - name: p["name"], - description: p["description"], - parameters: p["parameters"], - })), - function_call: body["functionCall"], - max_tokens: body["maxTokens"], - temperature: body["temperature"], - top_p: body["topP"], - logit_bias: body["logitBias"], - user: body["user"], - n: body["n"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - stream: body["stream"], - model: body["model"], - dataSources: !body["dataSources"] - ? body["dataSources"] - : body["dataSources"].map((p) => ({ type: p["type"] })), - enhancements: !body.enhancements - ? undefined - : { - grounding: !body.enhancements?.grounding - ? undefined - : { enabled: body.enhancements?.grounding?.["enabled"] }, - ocr: !body.enhancements?.ocr - ? undefined - : { enabled: body.enhancements?.ocr?.["enabled"] }, - }, - seed: body["seed"], - response_format: body["responseFormat"], - tools: !body["tools"] - ? body["tools"] - : body["tools"].map((p) => ({ type: p["type"] })), - tool_choice: body["toolChoice"], - } as any, - }); -} - -export async function _getChatCompletionsWithAzureExtensionsDeserialize( - result: - | GetChatCompletionsWithAzureExtensions200Response - | GetChatCompletionsWithAzureExtensionsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - id: result.body["id"], - created: new Date(result.body["created"]), - choices: result.body["choices"].map((p) => ({ - message: !p.message ? undefined : (p.message as any), - index: p["index"], - finishReason: p["finish_reason"], - finishDetails: !p.finish_details - ? undefined - : { type: p.finish_details?.["type"] }, - delta: !p.delta - ? undefined - : { - role: p.delta?.["role"], - content: p.delta?.["content"], - toolCalls: !p.delta?.["tool_calls"] - ? p.delta?.["tool_calls"] - : p.delta?.["tool_calls"].map((p) => ({ - type: p["type"], - id: p["id"], - })), - functionCall: !p.delta?.function_call - ? undefined - : { - name: p.delta?.function_call?.["name"], - arguments: p.delta?.function_call?.["arguments"], - }, - context: !p.delta?.context - ? undefined - : { - messages: !p.delta?.context?.messages - ? undefined - : (p.delta?.context?.messages as any), - }, - }, - contentFilterResults: !p.content_filter_results - ? undefined - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - severity: p.content_filter_results?.sexual?.["severity"], - filtered: p.content_filter_results?.sexual?.["filtered"], - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - severity: p.content_filter_results?.violence?.["severity"], - filtered: p.content_filter_results?.violence?.["filtered"], - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - severity: p.content_filter_results?.hate?.["severity"], - filtered: p.content_filter_results?.hate?.["filtered"], - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - severity: p.content_filter_results?.self_harm?.["severity"], - filtered: p.content_filter_results?.self_harm?.["filtered"], - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: p.content_filter_results?.profanity?.["filtered"], - detected: p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.["custom_blocklists"] - ? p.content_filter_results?.["custom_blocklists"] - : p.content_filter_results?.["custom_blocklists"].map((p) => ({ - id: p["id"], - filtered: p["filtered"], - })), - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - protectedMaterialText: !p.content_filter_results - ?.protected_material_text - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_text?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_text?.[ - "detected" - ], - }, - protectedMaterialCode: !p.content_filter_results - ?.protected_material_code - ? undefined - : { - filtered: - p.content_filter_results?.protected_material_code?.[ - "filtered" - ], - detected: - p.content_filter_results?.protected_material_code?.[ - "detected" - ], - url: p.content_filter_results?.protected_material_code?.[ - "URL" - ], - license: - p.content_filter_results?.protected_material_code?.[ - "license" - ], - }, - }, - enhancements: { - grounding: !p.enhancements?.grounding - ? undefined - : { - lines: p.enhancements.grounding?.["lines"].map((p) => ({ - text: p["text"], - spans: p["spans"].map((p) => ({ - text: p["text"], - offset: p["offset"], - length: p["length"], - polygon: p["polygon"].map((p) => ({ x: p["x"], y: p["y"] })), - })), - })), - }, - }, - })), - promptFilterResults: !result.body["prompt_filter_results"] - ? result.body["prompt_filter_results"] - : result.body["prompt_filter_results"].map((p) => ({ - promptIndex: p["prompt_index"], - contentFilterResults - : { - sexual: !p.content_filter_results?.sexual - ? undefined - : { - severity: p.content_filter_results?.sexual?.["severity"], - filtered: p.content_filter_results?.sexual?.["filtered"], - }, - violence: !p.content_filter_results?.violence - ? undefined - : { - severity: - p.content_filter_results?.violence?.["severity"], - filtered: - p.content_filter_results?.violence?.["filtered"], - }, - hate: !p.content_filter_results?.hate - ? undefined - : { - severity: p.content_filter_results?.hate?.["severity"], - filtered: p.content_filter_results?.hate?.["filtered"], - }, - selfHarm: !p.content_filter_results?.self_harm - ? undefined - : { - severity: - p.content_filter_results?.self_harm?.["severity"], - filtered: - p.content_filter_results?.self_harm?.["filtered"], - }, - profanity: !p.content_filter_results?.profanity - ? undefined - : { - filtered: - p.content_filter_results?.profanity?.["filtered"], - detected: - p.content_filter_results?.profanity?.["detected"], - }, - customBlocklists: !p.content_filter_results?.[ - "custom_blocklists" - ] - ? p.content_filter_results?.["custom_blocklists"] - : p.content_filter_results?.["custom_blocklists"].map( - (p) => ({ id: p["id"], filtered: p["filtered"] }) - ), - error: !p.content_filter_results?.error - ? undefined - : p.content_filter_results?.error, - jailbreak: !p.content_filter_results?.jailbreak - ? undefined - : { - filtered: - p.content_filter_results?.jailbreak?.["filtered"], - detected: - p.content_filter_results?.jailbreak?.["detected"], - }, - }, - })), - systemFingerprint: result.body["system_fingerprint"], - usage: { - completionTokens: result.body.usage["completion_tokens"], - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; -} - -/** - * Gets chat completions for the provided chat messages. - * This is an Azure-specific version of chat completions that supports integration with configured data sources and - * other augmentations to the base chat completions capabilities. - */ -export async function getChatCompletionsWithAzureExtensions( - context: Client, - deploymentId: string, - body: ChatCompletionsOptions, - options: ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions = { - requestOptions: {}, - } -): Promise { - const result = await _getChatCompletionsWithAzureExtensionsSend( - context, - deploymentId, - body, - options - ); - return _getChatCompletionsWithAzureExtensionsDeserialize(result); -} - -export function _getImageGenerationsSend( - context: Client, - deploymentId: string, - body: ImageGenerationOptions, - options: ClientOpenAIClientGetImageGenerationsOptions = { requestOptions: {} } -): StreamableMethod< - GetImageGenerations200Response | GetImageGenerationsDefaultResponse -> { - return context - .path("/deployments/{deploymentId}/images/generations", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - body: { - model: body["model"], - prompt: body["prompt"], - n: body["n"], - size: body["size"], - response_format: body["responseFormat"], - quality: body["quality"], - style: body["style"], - user: body["user"], - }, - }); -} - -export async function _getImageGenerationsDeserialize( - result: GetImageGenerations200Response | GetImageGenerationsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body.error; - } - - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p) => ({ - url: p["url"], - base64Data: p["b64_json"], - revisedPrompt: p["revised_prompt"], - })), - }; -} - -/** Creates an image given a prompt. */ -export async function getImageGenerations( - context: Client, - deploymentId: string, - body: ImageGenerationOptions, - options: ClientOpenAIClientGetImageGenerationsOptions = { requestOptions: {} } -): Promise { - const result = await _getImageGenerationsSend( - context, - deploymentId, - body, - options - ); - return _getImageGenerationsDeserialize(result); -} - -export function _getEmbeddingsSend( - context: Client, - deploymentId: string, - body: EmbeddingsOptions, - options: ClientOpenAIClientGetEmbeddingsOptions = { requestOptions: {} } -): StreamableMethod { - return context - .path("/deployments/{deploymentId}/embeddings", deploymentId) - .post({ - ...operationOptionsToRequestParameters(options), - body: { user: body["user"], model: body["model"], input: body["input"] }, - }); -} - -export async function _getEmbeddingsDeserialize( - result: GetEmbeddings200Response | GetEmbeddingsDefaultResponse -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - data: result.body["data"].map((p) => ({ - embedding: p["embedding"], - index: p["index"], - })), - usage: { - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; -} - -/** Return the embeddings for a given prompt. */ -export async function getEmbeddings( - context: Client, - deploymentId: string, - body: EmbeddingsOptions, - options: ClientOpenAIClientGetEmbeddingsOptions = { requestOptions: {} } -): Promise { - const result = await _getEmbeddingsSend(context, deploymentId, body, options); - return _getEmbeddingsDeserialize(result); -} diff --git a/sdk/openai/openai/sources/generated/src/api/index.ts b/sdk/openai/openai/sources/generated/src/api/index.ts deleted file mode 100644 index 7e52c3e77f99..000000000000 --- a/sdk/openai/openai/sources/generated/src/api/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -export { - createOpenAI, - OpenAIClientOptions, - OpenAIContext, -} from "./OpenAIContext.js"; diff --git a/sdk/openai/openai/sources/generated/src/classic/client/index.ts b/sdk/openai/openai/sources/generated/src/classic/client/index.ts deleted file mode 100644 index 55c68c98e0c2..000000000000 --- a/sdk/openai/openai/sources/generated/src/classic/client/index.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { OpenAIContext } from "../../api/OpenAIContext.js"; -import { - ClientOpenAIClientOperations, - getClientOpenAIClientOperations, -} from "./openAIClient/index.js"; - -export interface ClientOperations { - openAIClient: ClientOpenAIClientOperations; -} - -export function getClientOperations(context: OpenAIContext): ClientOperations { - return { - openAIClient: getClientOpenAIClientOperations(context), - }; -} diff --git a/sdk/openai/openai/sources/generated/src/classic/client/openAIClient/index.ts b/sdk/openai/openai/sources/generated/src/classic/client/openAIClient/index.ts deleted file mode 100644 index 8a6f2274e9b0..000000000000 --- a/sdk/openai/openai/sources/generated/src/classic/client/openAIClient/index.ts +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { OpenAIContext } from "../../../api/OpenAIContext.js"; -import { - AudioTranscriptionOptions, - AudioTranscription, - AudioTranslationOptions, - AudioTranslation, - CompletionsOptions, - Completions, - ChatCompletionsOptions, - ChatCompletions, - ImageGenerationOptions, - ImageGenerations, - EmbeddingsOptions, - Embeddings, -} from "../../../models/models.js"; -import { - getAudioTranscriptionAsPlainText, - getAudioTranscriptionAsResponseObject, - getAudioTranslationAsPlainText, - getAudioTranslationAsResponseObject, - getCompletions, - getChatCompletions, - getChatCompletionsWithAzureExtensions, - getImageGenerations, - getEmbeddings, -} from "../../../api/client/openAIClient/index.js"; -import { - ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ClientOpenAIClientGetCompletionsOptions, - ClientOpenAIClientGetChatCompletionsOptions, - ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ClientOpenAIClientGetImageGenerationsOptions, - ClientOpenAIClientGetEmbeddingsOptions, -} from "../../../models/options.js"; - -export interface ClientOpenAIClientOperations { - getAudioTranscriptionAsPlainText: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions - ) => Promise; - getAudioTranscriptionAsResponseObject: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions - ) => Promise; - getAudioTranslationAsPlainText: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions - ) => Promise; - getAudioTranslationAsResponseObject: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions - ) => Promise; - getCompletions: ( - deploymentId: string, - body: CompletionsOptions, - options?: ClientOpenAIClientGetCompletionsOptions - ) => Promise; - getChatCompletions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsOptions - ) => Promise; - getChatCompletionsWithAzureExtensions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions - ) => Promise; - getImageGenerations: ( - deploymentId: string, - body: ImageGenerationOptions, - options?: ClientOpenAIClientGetImageGenerationsOptions - ) => Promise; - getEmbeddings: ( - deploymentId: string, - body: EmbeddingsOptions, - options?: ClientOpenAIClientGetEmbeddingsOptions - ) => Promise; -} - -export function getClientOpenAIClient(context: OpenAIContext) { - return { - getAudioTranscriptionAsPlainText: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions - ) => getAudioTranscriptionAsPlainText(context, deploymentId, body, options), - getAudioTranscriptionAsResponseObject: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions - ) => - getAudioTranscriptionAsResponseObject( - context, - deploymentId, - body, - options - ), - getAudioTranslationAsPlainText: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions - ) => getAudioTranslationAsPlainText(context, deploymentId, body, options), - getAudioTranslationAsResponseObject: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions - ) => - getAudioTranslationAsResponseObject(context, deploymentId, body, options), - getCompletions: ( - deploymentId: string, - body: CompletionsOptions, - options?: ClientOpenAIClientGetCompletionsOptions - ) => getCompletions(context, deploymentId, body, options), - getChatCompletions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsOptions - ) => getChatCompletions(context, deploymentId, body, options), - getChatCompletionsWithAzureExtensions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions - ) => - getChatCompletionsWithAzureExtensions( - context, - deploymentId, - body, - options - ), - getImageGenerations: ( - deploymentId: string, - body: ImageGenerationOptions, - options?: ClientOpenAIClientGetImageGenerationsOptions - ) => getImageGenerations(context, deploymentId, body, options), - getEmbeddings: ( - deploymentId: string, - body: EmbeddingsOptions, - options?: ClientOpenAIClientGetEmbeddingsOptions - ) => getEmbeddings(context, deploymentId, body, options), - }; -} - -export function getClientOpenAIClientOperations( - context: OpenAIContext -): ClientOpenAIClientOperations { - return { - ...getClientOpenAIClient(context), - }; -} diff --git a/sdk/openai/openai/sources/generated/src/classic/index.ts b/sdk/openai/openai/sources/generated/src/classic/index.ts deleted file mode 100644 index b6e05733141a..000000000000 --- a/sdk/openai/openai/sources/generated/src/classic/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -export { ClientOperations } from "./client/index.js"; -export { ClientOpenAIClientOperations } from "./client/openAIClient/index.js"; diff --git a/sdk/openai/openai/sources/generated/src/models/options.ts b/sdk/openai/openai/sources/generated/src/models/options.ts deleted file mode 100644 index 24aea2b2e410..000000000000 --- a/sdk/openai/openai/sources/generated/src/models/options.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { OperationOptions } from "@azure-rest/core-client"; - -export interface ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions - extends OperationOptions {} - -export interface ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions - extends OperationOptions { - /** The content type for the operation. Always multipart/form-data for this operation. */ - contentType?: string; -} - -export interface ClientOpenAIClientGetAudioTranslationAsPlainTextOptions - extends OperationOptions {} - -export interface ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions - extends OperationOptions { - /** The content type for the operation. Always multipart/form-data for this operation. */ - contentType?: string; -} - -export interface ClientOpenAIClientGetCompletionsOptions - extends OperationOptions {} - -export interface ClientOpenAIClientGetChatCompletionsOptions - extends OperationOptions {} - -export interface ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions - extends OperationOptions {} - -export interface ClientOpenAIClientGetImageGenerationsOptions - extends OperationOptions {} - -export interface ClientOpenAIClientGetEmbeddingsOptions - extends OperationOptions {} diff --git a/sdk/openai/openai/src/OpenAIClient.ts b/sdk/openai/openai/src/OpenAIClient.ts index 709ffe1c2d26..62fd7169f5fa 100644 --- a/sdk/openai/openai/src/OpenAIClient.ts +++ b/sdk/openai/openai/src/OpenAIClient.ts @@ -1,53 +1,49 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - -import { KeyCredential, TokenCredential, isTokenCredential } from "@azure/core-auth"; +import { TokenCredential, KeyCredential, isTokenCredential } from "@azure/core-auth"; import { - getAudioTranscription, - getAudioTranslation, - getImages, - streamChatCompletions, - streamCompletions, -} from "./api/index.js"; + Completions, + ChatCompletions, + ImageGenerations, + Embeddings, + ChatRequestMessageUnion, + EventStream, +} from "./models/models.js"; +import { + GetCompletionsOptions, + GetChatCompletionsOptions, + GetEmbeddingsOptions, + GetImagesOptions, +} from "./models/options.js"; +import { createOpenAI, OpenAIClientOptions, OpenAIContext } from "./api/index.js"; import { - getChatCompletions, getCompletions, + getChatCompletions, + getImageGenerations, getEmbeddings, -} from "./api/client/openAIClient/index.js"; -import { OpenAIClientOptions, OpenAIContext, createOpenAI } from "./api/index.js"; + getAudioTranscription, + getAudioTranslation, +} from "./api/operations.js"; import { nonAzurePolicy } from "./api/policies/nonAzure.js"; +import { streamChatCompletions, streamCompletions } from "./api/operations.js"; import { - AudioResult, - AudioResultFormat, - AudioResultSimpleJson, GetAudioTranscriptionOptions, + AudioResultSimpleJson, + AudioResultFormat, + AudioResult, GetAudioTranslationOptions, } from "./models/audio.js"; -import { - GetImagesOptions, - GetCompletionsOptions, - GetEmbeddingsOptions, - GetChatCompletionsOptions, -} from "./models/options.js"; -import { - ChatCompletions, - ChatRequestMessage, - Completions, - Embeddings, - EventStream, - ImageGenerations, -} from "./models/models.js"; -export { OpenAIClientOptions } from "./api/OpenAIContext.js"; +function createOpenAIEndpoint(version: number): string { + return `https://api.openai.com/v${version}`; +} + +function isCred(cred: Record): cred is TokenCredential | KeyCredential { + return isTokenCredential(cred) || cred.key !== undefined; +} +export { OpenAIClientOptions } from "./api/OpenAIContext.js"; /** * A client for interacting with Azure OpenAI. * @@ -138,7 +134,6 @@ export class OpenAIClient { ...restOpts, }; } - this._client = createOpenAI(endpoint, cred, { ...opts, ...(this._isAzure @@ -155,100 +150,55 @@ export class OpenAIClient { }); } - /** - * Returns textual completions as configured for a given prompt. - * @param deploymentName - Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param prompt - The prompt to use for this request. - * @param options - The options for this completions request. - * @returns The completions for the given prompt. - */ - getCompletions( - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = { requestOptions: {} }, - ): Promise { - this.setModel(deploymentName, options); - return getCompletions(this._client, deploymentName, prompt, options); - } - - /** - * Lists the completions tokens as they become available for a given prompt. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param prompt - The prompt to use for this request. - * @param options - The completions options for this completions request. - * @returns An asynchronous iterable of completions tokens. - */ - streamCompletions( - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = {}, - ): Promise>> { - this.setModel(deploymentName, options); - return streamCompletions(this._client, deploymentName, prompt, options); - } - - /** - * Return the computed embeddings for a given prompt. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param input - The prompt to use for this request. - * @param options - The embeddings options for this embeddings request. - * @returns The embeddings for the given prompt. - */ - getEmbeddings( - deploymentName: string, - input: string[], - options: GetEmbeddingsOptions = { requestOptions: {} }, - ): Promise { - this.setModel(deploymentName, options); - return getEmbeddings(this._client, deploymentName, { input, ...options }, options); + private setModel(model: string, options: Record): void { + if (!this._isAzure) { + options.model = model; + } } /** - * Get chat completions for provided chat context messages. + * Returns the translation of an audio file. * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param messages - The chat context messages to use for this request. - * @param options - The chat completions options for this completions request. - * @returns The chat completions for the given chat context messages. + * @param fileContent - The content of the audio file to translate. + * @param options - The options for this audio translation request. + * @returns The audio translation result. */ - getChatCompletions( + async getAudioTranslation( deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, - ): Promise { - this.setModel(deploymentName, options); - return getChatCompletions(this._client, deploymentName, messages, options); - } - + fileContent: Uint8Array, + options?: GetAudioTranslationOptions, + ): Promise; /** - * Lists the chat completions tokens as they become available for a chat context. + * Returns the translation of an audio file. * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param messages - The chat context messages to use for this request. - * @param options - The chat completions options for this chat completions request. - * @returns An asynchronous iterable of chat completions tokens. + * @param fileContent - The content of the audio file to translate. + * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. + * @param options - The options for this audio translation request. + * @returns The audio translation result. */ - streamChatCompletions( + async getAudioTranslation( deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, - ): Promise> { - this.setModel(deploymentName, options); - return streamChatCompletions(this._client, deploymentName, messages, options); - } - - /** - * Starts the generation of a batch of images from a text caption - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param prompt - The prompt to use for this request. - * @param options - The options for this image request. - * @returns The image generation response (containing url or base64 data). - */ - getImages( + fileContent: Uint8Array, + format: Format, + options?: GetAudioTranslationOptions, + ): Promise>; + // implementation + async getAudioTranslation( deploymentName: string, - prompt: string, - options: GetImagesOptions = { requestOptions: {} }, - ): Promise { + fileContent: Uint8Array, + formatOrOptions?: Format | GetAudioTranslationOptions, + inputOptions?: GetAudioTranslationOptions, + ): Promise> { + const options = + inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); + const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; this.setModel(deploymentName, options); - return getImages(this._client, deploymentName, prompt, options); + if (response_format === undefined) { + return getAudioTranslation(this._client, deploymentName, fileContent, options) as Promise< + AudioResult + >; + } + return getAudioTranslation(this._client, deploymentName, fileContent, response_format, options); } /** @@ -277,6 +227,7 @@ export class OpenAIClient { format: Format, options?: GetAudioTranscriptionOptions, ): Promise>; + // implementation async getAudioTranscription( deploymentName: string, fileContent: Uint8Array, @@ -292,7 +243,6 @@ export class OpenAIClient { AudioResult >; } - return getAudioTranscription( this._client, deploymentName, @@ -303,61 +253,100 @@ export class OpenAIClient { } /** - * Returns the translation of an audio file. - * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. - * @param options - The options for this audio translation request. - * @returns The audio translation result. + * Gets completions for the provided input prompts. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. */ - async getAudioTranslation( + getCompletions( deploymentName: string, - fileContent: Uint8Array, - options?: GetAudioTranslationOptions, - ): Promise; + prompt: string[], + options: GetCompletionsOptions = { requestOptions: {} }, + ): Promise { + this.setModel(deploymentName, options); + const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; + return getCompletions( + this._client, + deploymentName, + { prompt, ...rest }, + { abortSignal, onResponse, requestOptions, tracingOptions }, + ); + } + /** - * Returns the translation of an audio file. + * Lists the completions tokens as they become available for a given prompt. * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. - * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. - * @param options - The options for this audio translation request. - * @returns The audio translation result. + * @param prompt - The prompt to use for this request. + * @param options - The completions options for this completions request. + * @returns An asynchronous iterable of completions tokens. */ - async getAudioTranslation( - deploymentName: string, - fileContent: Uint8Array, - format: Format, - options?: GetAudioTranslationOptions, - ): Promise>; - async getAudioTranslation( + streamCompletions( deploymentName: string, - fileContent: Uint8Array, - formatOrOptions?: Format | GetAudioTranslationOptions, - inputOptions?: GetAudioTranslationOptions, - ): Promise> { - const options = - inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); - const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; + prompt: string[], + options: GetCompletionsOptions = {}, + ): Promise>> { this.setModel(deploymentName, options); - if (response_format === undefined) { - return getAudioTranslation(this._client, deploymentName, fileContent, options) as Promise< - AudioResult - >; - } + return streamCompletions(this._client, deploymentName, prompt, options); + } - return getAudioTranslation(this._client, deploymentName, fileContent, response_format, options); + /** + * Gets chat completions for the provided chat messages. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ + getChatCompletions( + deploymentName: string, + messages: ChatRequestMessageUnion[], + options: GetChatCompletionsOptions = { requestOptions: {} }, + ): Promise { + this.setModel(deploymentName, options); + return getChatCompletions(this._client, deploymentName, messages, options); } - private setModel(model: string, options: Record): void { - if (!this._isAzure) { - options.model = model; - } + /** + * Lists the chat completions tokens as they become available for a chat context. + * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + * @param messages - The chat context messages to use for this request. + * @param options - The chat completions options for this chat completions request. + * @returns An asynchronous iterable of chat completions tokens. + */ + streamChatCompletions( + deploymentName: string, + messages: ChatRequestMessageUnion[], + options: GetChatCompletionsOptions = { requestOptions: {} }, + ): Promise> { + this.setModel(deploymentName, options); + return streamChatCompletions(this._client, deploymentName, messages, options); } -} -function createOpenAIEndpoint(version: number): string { - return `https://api.openai.com/v${version}`; -} + /** Creates an image given a prompt. */ + getImages( + deploymentName: string, + prompt: string, + options: GetImagesOptions = { requestOptions: {} }, + ): Promise { + this.setModel(deploymentName, options); + const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; + return getImageGenerations( + this._client, + deploymentName, + { prompt, ...rest }, + { abortSignal, onResponse, requestOptions, tracingOptions }, + ); + } -function isCred(cred: Record): cred is TokenCredential | KeyCredential { - return isTokenCredential(cred) || cred.key !== undefined; + /** Return the embeddings for a given prompt. */ + getEmbeddings( + deploymentName: string, + input: string[], + options: GetEmbeddingsOptions = { requestOptions: {} }, + ): Promise { + this.setModel(deploymentName, options); + const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; + return getEmbeddings( + this._client, + deploymentName, + { input, ...rest }, + { abortSignal, onResponse, requestOptions, tracingOptions }, + ); + } } diff --git a/sdk/openai/openai/src/OpenAIKeyCredential.ts b/sdk/openai/openai/src/OpenAIKeyCredential.ts index fa68f211496f..faf0d7a62ab9 100644 --- a/sdk/openai/openai/src/OpenAIKeyCredential.ts +++ b/sdk/openai/openai/src/OpenAIKeyCredential.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { KeyCredential } from "@azure/core-auth"; /** diff --git a/sdk/openai/openai/src/api/OpenAIContext.ts b/sdk/openai/openai/src/api/OpenAIContext.ts index a3ac8ba021ff..0c1c89790ba9 100644 --- a/sdk/openai/openai/src/api/OpenAIContext.ts +++ b/sdk/openai/openai/src/api/OpenAIContext.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { TokenCredential, KeyCredential } from "@azure/core-auth"; import { ClientOptions } from "@azure-rest/core-client"; import { OpenAIContext } from "../rest/index.js"; diff --git a/sdk/openai/openai/src/api/client/openAIClient/deserializers.ts b/sdk/openai/openai/src/api/client/openAIClient/deserializers.ts deleted file mode 100644 index 7dd33a0b8548..000000000000 --- a/sdk/openai/openai/src/api/client/openAIClient/deserializers.ts +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - -import { ErrorModel } from "@azure-rest/core-client"; -import { - ChatCompletions, - ChatResponseMessage, - Completions, - ContentFilterResultDetailsForPrompt, - ContentFilterResultsForChoice, - ContentFilterResultsForPrompt, -} from "../../../models/models.js"; -import { - ChatCompletionsOutput, - ChatResponseMessageOutput, - CompletionsOutput, - ContentFilterResultDetailsForPromptOutput, - ContentFilterResultsForChoiceOutput, - ContentFilterResultsForPromptOutput, -} from "../../../rest/outputModels.js"; -import { camelCaseKeys } from "../../util.js"; - -type ContentFilterResultsForPromptX = { - prompt_filter_results?: Array; - prompt_annotations?: Array; -}; - -function getContentFilterResultsForPrompt({ - prompt_annotations, - prompt_filter_results, -}: ContentFilterResultsForPromptX): ContentFilterResultsForPrompt[] { - const res = prompt_filter_results ?? prompt_annotations; - return ( - res?.map(({ content_filter_results, ...rest }) => ({ - ...camelCaseKeys(rest), - contentFilterResults: parseContentFilterResultDetailsForPromptOutput(content_filter_results), - })) ?? [] - ); -} - -export function getCompletionsResult( - body: CompletionsOutput & ContentFilterResultsForPromptX, -): Completions { - const { created, choices, prompt_filter_results, prompt_annotations, ...rest } = body; - return { - ...camelCaseKeys(rest), - created: new Date(created), - promptFilterResults: getContentFilterResultsForPrompt({ - prompt_filter_results, - prompt_annotations, - }), - choices: choices.map(({ content_filter_results, ...choice }) => ({ - ...camelCaseKeys(choice), - ...(!content_filter_results - ? {} - : { - contentFilterResults: parseContentFilterResultsForChoiceOutput(content_filter_results), - }), - })), - }; -} - -export function getChatCompletionsResult( - body: ChatCompletionsOutput & ContentFilterResultsForPromptX, -): ChatCompletions { - const { created, choices, prompt_filter_results, prompt_annotations, ...rest } = body; - return { - ...camelCaseKeys(rest), - created: new Date(created), - promptFilterResults: getContentFilterResultsForPrompt({ - prompt_filter_results, - prompt_annotations, - }), - choices: !choices - ? [] - : choices.map(({ content_filter_results, delta, message, ...choice }) => ({ - ...camelCaseKeys(choice), - ...(!delta ? {} : { delta: parseMessage(delta) }), - ...(!message ? {} : { message: parseMessage(message) }), - ...(!content_filter_results - ? {} - : { - contentFilterResults: - parseContentFilterResultsForChoiceOutput(content_filter_results), - }), - })), - }; -} - -function parseMessage(message: ChatResponseMessageOutput): ChatResponseMessage { - const { context, tool_calls, ...rest } = message; - return { - ...camelCaseKeys(rest), - toolCalls: tool_calls ?? [], - ...(!context - ? {} - : { - context: { - ...(!context.messages - ? {} - : { - messages: context.messages.map(parseMessage), - }), - }, - }), - }; -} - -function parseError(error: ErrorModel): { error: ErrorModel } { - return { - error: { - ...error, - details: error["details"] ?? [], - }, - }; -} - -function parseContentFilterResultDetailsForPromptOutput({ - error, - ...rest -}: ContentFilterResultDetailsForPromptOutput = {}): ContentFilterResultDetailsForPrompt { - return error ? parseError(error) : camelCaseKeys(rest); -} - -function parseContentFilterResultsForChoiceOutput({ - error, - ...rest -}: ContentFilterResultsForChoiceOutput = {}): ContentFilterResultsForChoice { - return error ? parseError(error) : camelCaseKeys(rest); -} diff --git a/sdk/openai/openai/src/api/getSSEs.browser.ts b/sdk/openai/openai/src/api/getSSEs.browser.ts index f23d8c7236dd..b2733f49e2c7 100644 --- a/sdk/openai/openai/src/api/getSSEs.browser.ts +++ b/sdk/openai/openai/src/api/getSSEs.browser.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { StreamableMethod } from "@azure-rest/core-client"; import { wrapError } from "./util.js"; import { streamToText } from "./readableStreamUtils.js"; diff --git a/sdk/openai/openai/src/api/getSSEs.ts b/sdk/openai/openai/src/api/getSSEs.ts index f2a77f9efd59..637bde913444 100644 --- a/sdk/openai/openai/src/api/getSSEs.ts +++ b/sdk/openai/openai/src/api/getSSEs.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { StreamableMethod } from "@azure-rest/core-client"; import { RestError } from "@azure/core-rest-pipeline"; import { wrapError } from "./util.js"; diff --git a/sdk/openai/openai/src/api/index.ts b/sdk/openai/openai/src/api/index.ts index ce10ba7618eb..307a8ebb69fb 100644 --- a/sdk/openai/openai/src/api/index.ts +++ b/sdk/openai/openai/src/api/index.ts @@ -1,22 +1,14 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - -export { OpenAIClientOptions, OpenAIContext, createOpenAI } from "./OpenAIContext.js"; +export { createOpenAI, OpenAIClientOptions, OpenAIContext } from "./OpenAIContext.js"; export { getAudioTranscription, getAudioTranslation, + getCompletions, getChatCompletions, - getImages, streamChatCompletions, streamCompletions, + getImageGenerations, getEmbeddings, - getCompletions, -} from "./client/openAIClient/index.js"; +} from "./operations.js"; diff --git a/sdk/openai/openai/src/api/oaiSse.ts b/sdk/openai/openai/src/api/oaiSse.ts index 080a81b39a5e..4434f9ddbbd3 100644 --- a/sdk/openai/openai/src/api/oaiSse.ts +++ b/sdk/openai/openai/src/api/oaiSse.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { StreamableMethod } from "@azure-rest/core-client"; import { getStream } from "./getSSEs.js"; import { wrapError } from "./util.js"; diff --git a/sdk/openai/openai/src/api/client/openAIClient/index.ts b/sdk/openai/openai/src/api/operations.ts similarity index 51% rename from sdk/openai/openai/src/api/client/openAIClient/index.ts rename to sdk/openai/openai/src/api/operations.ts index 98c1f32c1c1c..3cf19c670417 100644 --- a/sdk/openai/openai/src/api/client/openAIClient/index.ts +++ b/sdk/openai/openai/src/api/operations.ts @@ -1,64 +1,25 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - -import { StreamableMethod, operationOptionsToRequestParameters } from "@azure-rest/core-client"; -import { createFile } from "@azure/core-rest-pipeline"; -import { uint8ArrayToString } from "@azure/core-util"; import { - AudioResult, - AudioResultFormat, - AudioResultSimpleJson, - GetAudioTranscriptionOptions, - GetAudioTranslationOptions, -} from "../../../models/audio.js"; -import { - AudioTranscription, - AudioTranscriptionOptions, - AudioTranslation, - AudioTranslationOptions, - ChatCompletions, - ChatCompletionsOptions, - ChatRequestMessage, - Completions, CompletionsOptions, - Embeddings, + Completions, + ChatCompletionsOptions, + ChatCompletions, + ImageGenerationOptions, + ImageGenerations, EmbeddingsOptions, + Embeddings, + ChatRequestMessageUnion, EventStream, - ImageGenerations, -} from "../../../models/models.js"; -import { - ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ClientOpenAIClientGetChatCompletionsOptions, - ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ClientOpenAIClientGetCompletionsOptions, - ClientOpenAIClientGetEmbeddingsOptions, - ClientOpenAIClientGetImageGenerationsOptions, - GetChatCompletionsOptions, - GetCompletionsOptions, - GetImagesOptions, -} from "../../../models/options.js"; + ChatResponseMessage, + ContentFilterResultsForChoice, + ContentFilterResultDetailsForPrompt, + ContentFilterResultsForPrompt, +} from "../models/models.js"; +import { serializeChatRequestMessageUnion } from "../utils/serializeUtil.js"; import { AzureChatExtensionConfiguration, - OpenAIContext as Client, - GetAudioTranscriptionAsPlainText200Response, - GetAudioTranscriptionAsPlainTextDefaultResponse, - GetAudioTranscriptionAsResponseObject200Response, - GetAudioTranscriptionAsResponseObjectDefaultResponse, - GetAudioTranslationAsPlainText200Response, - GetAudioTranslationAsPlainTextDefaultResponse, - GetAudioTranslationAsResponseObject200Response, - GetAudioTranslationAsResponseObjectDefaultResponse, GetChatCompletions200Response, GetChatCompletionsDefaultResponse, GetChatCompletionsWithAzureExtensions200Response, @@ -70,543 +31,83 @@ import { GetImageGenerations200Response, GetImageGenerationsDefaultResponse, isUnexpected, - ChatRequestMessage as RestChatRequestMessage, -} from "../../../rest/index.js"; -import { getOaiSSEs } from "../../oaiSse.js"; -import { camelCaseKeys, snakeCaseKeys } from "../../util.js"; -import { getChatCompletionsResult, getCompletionsResult } from "./deserializers.js"; + OpenAIContext as Client, + ChatResponseMessageOutput, + ContentFilterResultsForChoiceOutput, + ContentFilterResultDetailsForPromptOutput, + ContentFilterResultsForPromptOutput, + ChatCompletionsOutput, + CompletionsOutput, +} from "../rest/index.js"; import { - ChatCompletionsOptions as GeneratedChatCompletionsOptions, - ImageGenerationOptions as GeneratedImageGenerationOptions, -} from "../../../models/models.js"; - -export function _getAudioTranscriptionAsPlainTextSend( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions = { - requestOptions: {}, - }, -): StreamableMethod< - GetAudioTranscriptionAsPlainText200Response | GetAudioTranscriptionAsPlainTextDefaultResponse -> { - return context.path("/deployments/{deploymentId}/audio/transcriptions", deploymentId).post({ - ...operationOptionsToRequestParameters(options), - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - language: body["language"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - GetAudioTranscriptionAsPlainText200Response | GetAudioTranscriptionAsPlainTextDefaultResponse - >; -} - -export async function _getAudioTranscriptionAsPlainTextDeserialize( - result: - | GetAudioTranscriptionAsPlainText200Response - | GetAudioTranscriptionAsPlainTextDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return result.body; -} - -/** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. - */ -export async function getAudioTranscriptionAsPlainText( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranscriptionAsPlainTextSend(context, deploymentId, body, options); - return _getAudioTranscriptionAsPlainTextDeserialize(result); -} - -export function _getAudioTranscriptionAsResponseObjectSend( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions = { - requestOptions: {}, - }, -): StreamableMethod< - | GetAudioTranscriptionAsResponseObject200Response - | GetAudioTranscriptionAsResponseObjectDefaultResponse -> { - return context.path("/deployments/{deploymentId}/audio/transcriptions", deploymentId).post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - language: body["language"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - | GetAudioTranscriptionAsResponseObject200Response - | GetAudioTranscriptionAsResponseObjectDefaultResponse - >; -} - -export async function _getAudioTranscriptionAsResponseObjectDeserialize( - result: - | GetAudioTranscriptionAsResponseObject200Response - | GetAudioTranscriptionAsResponseObjectDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - text: result.body["text"], - task: result.body["task"], - language: result.body["language"], - duration: result.body["duration"], - segments: !result.body["segments"] - ? result.body["segments"] - : result.body["segments"].map((p) => ({ - id: p["id"], - start: p["start"], - end: p["end"], - text: p["text"], - temperature: p["temperature"], - avgLogprob: p["avg_logprob"], - compressionRatio: p["compression_ratio"], - noSpeechProb: p["no_speech_prob"], - tokens: p["tokens"], - seek: p["seek"], - })), - }; -} - -/** - * Gets transcribed text and associated metadata from provided spoken audio data. Audio will be transcribed in the - * written language corresponding to the language it was spoken in. - */ -export async function getAudioTranscriptionAsResponseObject( - context: Client, - deploymentId: string, - body: AudioTranscriptionOptions, - options: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranscriptionAsResponseObjectSend( - context, - deploymentId, - body, - options, - ); - return _getAudioTranscriptionAsResponseObjectDeserialize(result); -} - -export function _getAudioTranslationAsPlainTextSend( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions = { - requestOptions: {}, - }, -): StreamableMethod< - GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsPlainTextDefaultResponse -> { - return context.path("/deployments/{deploymentId}/audio/translations", deploymentId).post({ - ...operationOptionsToRequestParameters(options), - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsPlainTextDefaultResponse - >; -} - -export async function _getAudioTranslationAsPlainTextDeserialize( - result: GetAudioTranslationAsPlainText200Response | GetAudioTranslationAsPlainTextDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return result.body; -} - -/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ -export async function getAudioTranslationAsPlainText( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranslationAsPlainTextSend(context, deploymentId, body, options); - return _getAudioTranslationAsPlainTextDeserialize(result); -} - -export function _getAudioTranslationAsResponseObjectSend( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions = { - requestOptions: {}, - }, -): StreamableMethod< - | GetAudioTranslationAsResponseObject200Response - | GetAudioTranslationAsResponseObjectDefaultResponse -> { - return context.path("/deployments/{deploymentId}/audio/translations", deploymentId).post({ - ...operationOptionsToRequestParameters(options), - contentType: (options.contentType as any) ?? "multipart/form-data", - body: { - file: uint8ArrayToString(body["file"], "base64"), - filename: body["filename"], - response_format: body["responseFormat"], - prompt: body["prompt"], - temperature: body["temperature"], - model: body["model"], - }, - }) as StreamableMethod< - | GetAudioTranslationAsResponseObject200Response - | GetAudioTranslationAsResponseObjectDefaultResponse - >; -} - -export async function _getAudioTranslationAsResponseObjectDeserialize( - result: - | GetAudioTranslationAsResponseObject200Response - | GetAudioTranslationAsResponseObjectDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body; - } - - return { - text: result.body["text"], - task: result.body["task"], - language: result.body["language"], - duration: result.body["duration"], - segments: !result.body["segments"] - ? result.body["segments"] - : result.body["segments"].map((p) => ({ - id: p["id"], - start: p["start"], - end: p["end"], - text: p["text"], - temperature: p["temperature"], - avgLogprob: p["avg_logprob"], - compressionRatio: p["compression_ratio"], - noSpeechProb: p["no_speech_prob"], - tokens: p["tokens"], - seek: p["seek"], - })), - }; -} - -/** Gets English language transcribed text and associated metadata from provided spoken audio data. */ -export async function getAudioTranslationAsResponseObject( - context: Client, - deploymentId: string, - body: AudioTranslationOptions, - options: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions = { - requestOptions: {}, - }, -): Promise { - const result = await _getAudioTranslationAsResponseObjectSend( - context, - deploymentId, - body, - options, - ); - return _getAudioTranslationAsResponseObjectDeserialize(result); -} - -export function _getCompletionsSend( - context: Client, - deploymentId: string, - body: CompletionsOptions, - options: ClientOpenAIClientGetCompletionsOptions = { requestOptions: {} }, -): StreamableMethod { - return context.path("/deployments/{deploymentId}/completions", deploymentId).post({ - ...operationOptionsToRequestParameters(options), - body: { - prompt: body["prompt"], - max_tokens: body["maxTokens"], - temperature: body["temperature"], - top_p: body["topP"], - logit_bias: body["logitBias"], - user: body["user"], - n: body["n"], - logprobs: body["logprobs"], - echo: body["echo"], - stop: body["stop"], - presence_penalty: body["presencePenalty"], - frequency_penalty: body["frequencyPenalty"], - best_of: body["bestOf"], - stream: body["stream"], - model: body["model"], - }, - }); -} - -/** - * Gets completions for the provided input prompts. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export async function getCompletions( - context: Client, - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = { requestOptions: {} }, -): Promise { - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const response = await _getCompletionsSend( - context, - deploymentName, - { - prompt, - ...rest, - }, - { abortSignal, onResponse, requestOptions, tracingOptions }, - ); - return _getCompletionsDeserialize(response); -} - -export async function _getCompletionsDeserialize( - result: GetCompletions200Response | GetCompletionsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body.error; - } - return getCompletionsResult(result.body); -} - -export async function _getChatCompletionsDeserialize( - result: GetChatCompletions200Response | GetChatCompletionsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body.error; - } - return getChatCompletionsResult(result.body); -} - -export function _getImageGenerationsSend( - context: Client, - deploymentId: string, - body: GeneratedImageGenerationOptions, - options: ClientOpenAIClientGetImageGenerationsOptions = { requestOptions: {} }, -): StreamableMethod { - return context.path("/deployments/{deploymentId}/images/generations", deploymentId).post({ - ...operationOptionsToRequestParameters(options), - body: { - model: body["model"], - prompt: body["prompt"], - n: body["n"], - size: body["size"], - response_format: body["responseFormat"], - quality: body["quality"], - style: body["style"], - user: body["user"], - }, - }); -} - -export async function _getImageGenerationsDeserialize( - result: GetImageGenerations200Response | GetImageGenerationsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body.error; - } - - return { - created: new Date(result.body["created"]), - data: result.body["data"].map((p) => ({ - url: p["url"], - base64Data: p["b64_json"], - revisedPrompt: p["revised_prompt"], - })), - }; -} - -/** Creates an image given a prompt. */ -export async function getImageGenerations( - context: Client, - deploymentId: string, - body: GeneratedImageGenerationOptions, - options: ClientOpenAIClientGetImageGenerationsOptions = { requestOptions: {} }, -): Promise { - const result = await _getImageGenerationsSend(context, deploymentId, body, options); - return _getImageGenerationsDeserialize(result); -} - -export function _getEmbeddingsSend( - context: Client, - deploymentId: string, - body: EmbeddingsOptions, - options: ClientOpenAIClientGetEmbeddingsOptions = { requestOptions: {} }, -): StreamableMethod { - return context.path("/deployments/{deploymentId}/embeddings", deploymentId).post({ - ...operationOptionsToRequestParameters(options), - body: { user: body["user"], model: body["model"], input: body["input"] }, - }); -} - -export async function _getEmbeddingsDeserialize( - result: GetEmbeddings200Response | GetEmbeddingsDefaultResponse, -): Promise { - if (isUnexpected(result)) { - throw result.body.error; - } - - return { - data: result.body["data"].map((p) => ({ - embedding: p["embedding"], - index: p["index"], - })), - usage: { - promptTokens: result.body.usage["prompt_tokens"], - totalTokens: result.body.usage["total_tokens"], - }, - }; -} - -/** Return the embeddings for a given prompt. */ -export async function getEmbeddings( - context: Client, - deploymentId: string, - body: EmbeddingsOptions, - options: ClientOpenAIClientGetEmbeddingsOptions = { requestOptions: {} }, -): Promise { - const result = await _getEmbeddingsSend(context, deploymentId, body, options); - return _getEmbeddingsDeserialize(result); -} - -export function streamCompletions( - context: Client, - deploymentName: string, - prompt: string[], - options: GetCompletionsOptions = { requestOptions: {} }, -): Promise>> { - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const response = _getCompletionsSend( - context, - deploymentName, - { - prompt, - ...rest, - stream: true, - }, - { abortSignal, onResponse, requestOptions, tracingOptions }, - ); - return getOaiSSEs(response, getCompletionsResult); -} - -export async function getImages( - context: Client, - deploymentName: string, - prompt: string, - options: GetImagesOptions = { requestOptions: {} }, -): Promise { - const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; - const result = await _getImageGenerationsSend( - context, - deploymentName, - { prompt, ...rest }, - { abortSignal, onResponse, requestOptions, tracingOptions }, - ); - return _getImageGenerationsDeserialize(result); -} - -export function streamChatCompletions( - context: Client, - deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, -): Promise> { - const response = _getChatCompletionsSendX(context, deploymentName, messages, { - ...options, - stream: true, - }); - return getOaiSSEs(response, getChatCompletionsResult); -} + StreamableMethod, + operationOptionsToRequestParameters, + ErrorModel, +} from "@azure-rest/core-client"; +import { + GetCompletionsOptions, + GetChatCompletionsOptions, + GetChatCompletionsWithAzureExtensionsOptions, + GetEmbeddingsOptions, + GetImagesOptions, + GetImageGenerationsOptions, + GeneratedGetChatCompletionsOptions, +} from "../models/options.js"; +import { getOaiSSEs } from "./oaiSse.js"; +import { createFile } from "@azure/core-rest-pipeline"; +import { + GetAudioTranscriptionOptions, + AudioResultSimpleJson, + AudioResultFormat, + AudioResult, + GetAudioTranslationOptions, +} from "../models/audio.js"; +import { snakeCaseKeys, camelCaseKeys } from "./util.js"; /** - * Gets chat completions for the provided chat messages. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. - */ -export async function getChatCompletions( - context: Client, - deploymentName: string, - messages: ChatRequestMessage[], - options: GetChatCompletionsOptions = { requestOptions: {} }, -): Promise { - const result = await _getChatCompletionsSendX(context, deploymentName, messages, options); - return _getChatCompletionsDeserialize(result); -} -/** - * Returns the translation of an audio file. + * Returns the transcription of an audio file in a simple JSON format. * @param context - The context containing the client to use for this request. * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. - * @param options - The options for this audio translation request. - * @returns The audio translation result. + * @param fileContent - The content of the audio file to transcribe. + * @param options - The options for this audio transcription request. + * @returns The audio transcription result in a simple JSON format. */ -export async function getAudioTranslation( +export async function getAudioTranscription( context: Client, deploymentName: string, fileContent: Uint8Array, - options?: GetAudioTranslationOptions, + options?: GetAudioTranscriptionOptions, ): Promise; /** - * Returns the translation of an audio file. + * Returns the transcription of an audio file. * @param context - The context containing the client to use for this request. * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to translate. + * @param fileContent - The content of the audio file to transcribe. * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. - * @param options - The options for this audio translation request. - * @returns The audio translation result. + * @param options - The options for this audio transcription request. + * @returns The audio transcription result in a format of your choice. */ -export async function getAudioTranslation( +export async function getAudioTranscription( context: Client, deploymentName: string, fileContent: Uint8Array, format: Format, - options?: GetAudioTranslationOptions, + options?: GetAudioTranscriptionOptions, ): Promise>; -export async function getAudioTranslation( +// implementation +export async function getAudioTranscription( context: Client, deploymentName: string, fileContent: Uint8Array, - formatOrOptions?: Format | GetAudioTranslationOptions, - inputOptions?: GetAudioTranslationOptions, + formatOrOptions?: Format | GetAudioTranscriptionOptions, + inputOptions?: GetAudioTranscriptionOptions, ): Promise> { const options = inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; const { body, status } = await context - .pathUnchecked("deployments/{deploymentName}/audio/translations", deploymentName) + .pathUnchecked("deployments/{deploymentName}/audio/transcriptions", deploymentName) .post({ ...operationOptionsToRequestParameters({ abortSignal, @@ -624,55 +125,55 @@ export async function getAudioTranslation( if (status !== "200") { throw body.error; } - return response_format !== "verbose_json" ? body : (camelCaseKeys(body) as unknown as AudioResult); } /** - * Returns the transcription of an audio file in a simple JSON format. + * Returns the translation of an audio file. * @param context - The context containing the client to use for this request. * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to transcribe. - * @param options - The options for this audio transcription request. - * @returns The audio transcription result in a simple JSON format. + * @param fileContent - The content of the audio file to translate. + * @param options - The options for this audio translation request. + * @returns The audio translation result. */ -export async function getAudioTranscription( +export async function getAudioTranslation( context: Client, deploymentName: string, fileContent: Uint8Array, - options?: GetAudioTranscriptionOptions, + options?: GetAudioTranslationOptions, ): Promise; /** - * Returns the transcription of an audio file. + * Returns the translation of an audio file. * @param context - The context containing the client to use for this request. * @param deploymentName - The name of the model deployment (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. - * @param fileContent - The content of the audio file to transcribe. + * @param fileContent - The content of the audio file to translate. * @param format - The format of the result object. See {@link AudioResultFormat} for possible values. - * @param options - The options for this audio transcription request. - * @returns The audio transcription result in a format of your choice. + * @param options - The options for this audio translation request. + * @returns The audio translation result. */ -export async function getAudioTranscription( +export async function getAudioTranslation( context: Client, deploymentName: string, fileContent: Uint8Array, format: Format, - options?: GetAudioTranscriptionOptions, + options?: GetAudioTranslationOptions, ): Promise>; -export async function getAudioTranscription( +// implementation +export async function getAudioTranslation( context: Client, deploymentName: string, fileContent: Uint8Array, - formatOrOptions?: Format | GetAudioTranscriptionOptions, - inputOptions?: GetAudioTranscriptionOptions, + formatOrOptions?: Format | GetAudioTranslationOptions, + inputOptions?: GetAudioTranslationOptions, ): Promise> { const options = inputOptions ?? (typeof formatOrOptions === "string" ? {} : formatOrOptions ?? {}); const response_format = typeof formatOrOptions === "string" ? formatOrOptions : undefined; const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; const { body, status } = await context - .pathUnchecked("deployments/{deploymentName}/audio/transcriptions", deploymentName) + .pathUnchecked("deployments/{deploymentName}/audio/translations", deploymentName) .post({ ...operationOptionsToRequestParameters({ abortSignal, @@ -690,16 +191,204 @@ export async function getAudioTranscription( if (status !== "200") { throw body.error; } - return response_format !== "verbose_json" ? body : (camelCaseKeys(body) as unknown as AudioResult); } +export function _getCompletionsSend( + context: Client, + deploymentId: string, + body: CompletionsOptions, + options: GetCompletionsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/completions", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { + prompt: body["prompt"], + max_tokens: body["maxTokens"], + temperature: body["temperature"], + top_p: body["topP"], + logit_bias: body["logitBias"], + user: body["user"], + n: body["n"], + logprobs: body["logprobs"], + echo: body["echo"], + stop: body["stop"], + presence_penalty: body["presencePenalty"], + frequency_penalty: body["frequencyPenalty"], + best_of: body["bestOf"], + stream: body["stream"], + model: body["model"], + }, + }); +} + +export async function _getCompletionsDeserialize( + result: GetCompletions200Response | GetCompletionsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw result.body.error; + } + + return getCompletionsResult(result.body); +} + +export function getCompletionsResult( + body: CompletionsOutput & ContentFilterResultsForPromptX, +): Completions { + const { created, choices, prompt_filter_results, prompt_annotations, ...rest } = body; + return { + ...camelCaseKeys(rest), + created: new Date(created), + promptFilterResults: getContentFilterResultsForPrompt({ + prompt_filter_results, + prompt_annotations, + }), + choices: choices.map(({ content_filter_results, ...choice }) => ({ + ...camelCaseKeys(choice), + ...(!content_filter_results + ? {} + : { + contentFilterResults: parseContentFilterResultsForChoiceOutput(content_filter_results), + }), + })), + }; +} + +/** + * Gets completions for the provided input prompts. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ +export async function getCompletions( + context: Client, + deploymentId: string, + body: CompletionsOptions, + options: GetCompletionsOptions = { requestOptions: {} }, +): Promise { + const result = await _getCompletionsSend(context, deploymentId, body, options); + return _getCompletionsDeserialize(result); +} + +export function streamCompletions( + context: Client, + deploymentName: string, + prompt: string[], + options: GetCompletionsOptions = { requestOptions: {} }, +): Promise>> { + const { abortSignal, onResponse, requestOptions, tracingOptions, ...rest } = options; + const response = _getCompletionsSend( + context, + deploymentName, + { + prompt, + ...rest, + stream: true, + }, + { abortSignal, onResponse, requestOptions, tracingOptions }, + ); + return getOaiSSEs(response, getCompletionsResult); +} + +export function _getChatCompletionsSend( + context: Client, + deploymentId: string, + body: ChatCompletionsOptions, + options: GeneratedGetChatCompletionsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/chat/completions", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { + model: body["model"], + stream: body["stream"], + max_tokens: body["maxTokens"], + temperature: body["temperature"], + top_p: body["topP"], + logit_bias: body["logitBias"], + user: body["user"], + n: body["n"], + stop: body["stop"], + presence_penalty: body["presencePenalty"], + frequency_penalty: body["frequencyPenalty"], + dataSources: body["dataSources"], + enhancements: !body.enhancements + ? undefined + : { + grounding: !body.enhancements?.grounding + ? undefined + : { enabled: body.enhancements?.grounding?.["enabled"] }, + ocr: !body.enhancements?.ocr + ? undefined + : { enabled: body.enhancements?.ocr?.["enabled"] }, + }, + seed: body["seed"], + response_format: !body.responseFormat ? undefined : { type: body.responseFormat?.["type"] }, + tool_choice: body["toolChoice"], + tools: body["tools"], + functions: body["functions"], + function_call: body["functionCall"], + messages: body["messages"].map((p) => serializeChatRequestMessageUnion(p)), + }, + }); +} + +export async function _getChatCompletionsDeserialize( + result: GetChatCompletions200Response | GetChatCompletionsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw result.body.error; + } + + return getChatCompletionsResult(result.body); +} + +export function getChatCompletionsResult( + body: ChatCompletionsOutput & ContentFilterResultsForPromptX, +): ChatCompletions { + const { created, choices, prompt_filter_results, prompt_annotations, ...rest } = body; + return { + ...camelCaseKeys(rest), + created: new Date(created), + promptFilterResults: getContentFilterResultsForPrompt({ + prompt_filter_results, + prompt_annotations, + }), + choices: !choices + ? [] + : choices.map(({ content_filter_results, delta, message, ...choice }) => ({ + ...camelCaseKeys(choice), + ...(!delta ? {} : { delta: parseMessage(delta) }), + ...(!message ? {} : { message: parseMessage(message) }), + ...(!content_filter_results + ? {} + : { + contentFilterResults: + parseContentFilterResultsForChoiceOutput(content_filter_results), + }), + })), + }; +} + +/** + * Gets chat completions for the provided chat messages. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ +export async function getChatCompletions( + context: Client, + deploymentName: string, + messages: ChatRequestMessageUnion[], + options: GetChatCompletionsOptions = { requestOptions: {} }, +): Promise { + const result = await _getChatCompletionsSendX(context, deploymentName, messages, options); + return _getChatCompletionsDeserialize(result); +} + function _getChatCompletionsSendX( context: Client, deploymentName: string, - messages: ChatRequestMessage[], + messages: ChatRequestMessageUnion[], options: GetChatCompletionsOptions & { stream?: boolean } = { requestOptions: {} }, ): StreamableMethod< | GetChatCompletionsWithAzureExtensions200Response @@ -741,80 +430,231 @@ function _getChatCompletionsSendX( : _getChatCompletionsSend(context, deploymentName, { messages, ...rest }, coreOptions); } -function _getChatCompletionsWithAzureExtensionsSend( +export function _getChatCompletionsWithAzureExtensionsSend( context: Client, - deploymentName: string, - body: GeneratedChatCompletionsOptions, - options: ClientOpenAIClientGetChatCompletionsOptions = { requestOptions: {} }, + deploymentId: string, + body: ChatCompletionsOptions, + options: GetChatCompletionsWithAzureExtensionsOptions = { + requestOptions: {}, + }, ): StreamableMethod< | GetChatCompletionsWithAzureExtensions200Response | GetChatCompletionsWithAzureExtensionsDefaultResponse > { - const { functions, functionCall, messages, dataSources, tools, ...rest } = body; return context - .path("/deployments/{deploymentId}/extensions/chat/completions", deploymentName) + .path("/deployments/{deploymentId}/extensions/chat/completions", deploymentId) .post({ ...operationOptionsToRequestParameters(options), body: { - ...snakeCaseKeys(rest), - tools, - dataSources: dataSources?.map( + max_tokens: body["maxTokens"], + temperature: body["temperature"], + top_p: body["topP"], + logit_bias: body["logitBias"], + user: body["user"], + n: body["n"], + stop: body["stop"], + presence_penalty: body["presencePenalty"], + frequency_penalty: body["frequencyPenalty"], + stream: body["stream"], + model: body["model"], + enhancements: !body.enhancements + ? undefined + : { + grounding: !body.enhancements?.grounding + ? undefined + : { enabled: body.enhancements?.grounding?.["enabled"] }, + ocr: !body.enhancements?.ocr + ? undefined + : { enabled: body.enhancements?.ocr?.["enabled"] }, + }, + seed: body["seed"], + response_format: !body.responseFormat ? undefined : { type: body.responseFormat?.["type"] }, + tool_choice: body["toolChoice"], + tools: body["tools"], + dataSources: body["dataSources"]?.map( ({ type, ...opts }) => ({ type, parameters: opts }) as AzureChatExtensionConfiguration, ), - functions, - function_call: functionCall, - messages: messages.map(serializeChatRequestMessage), + functions: + body["functions"] === undefined + ? body["functions"] + : body["functions"].map((p) => ({ + name: p["name"], + description: p["description"], + parameters: p["parameters"], + })), + function_call: body["functionCall"], + messages: body["messages"].map((p) => serializeChatRequestMessageUnion(p)), }, }); } -function serializeChatRequestMessage(message: ChatRequestMessage): RestChatRequestMessage { - if (message.content === undefined) { - message.content = null; - } - switch (message.role) { - case "assistant": { - const { functionCall, toolCalls, ...rest } = message; - return { - ...snakeCaseKeys(rest), - ...(!toolCalls || toolCalls.length === 0 ? {} : { tool_calls: toolCalls }), - ...(functionCall ? { function_call: functionCall } : {}), - }; - } - default: { - return snakeCaseKeys(message); - } - } +export function streamChatCompletions( + context: Client, + deploymentName: string, + messages: ChatRequestMessageUnion[], + options: GetChatCompletionsOptions = { requestOptions: {} }, +): Promise> { + const response = _getChatCompletionsSendX(context, deploymentName, messages, { + ...options, + stream: true, + }); + return getOaiSSEs(response, getChatCompletionsResult); } -function _getChatCompletionsSend( +export function _getImageGenerationsSend( context: Client, - deploymentName: string, - body: GeneratedChatCompletionsOptions, - options: ClientOpenAIClientGetChatCompletionsOptions = { requestOptions: {} }, -): StreamableMethod { - const { functions, functionCall, messages, tools, ...rest } = body; - return context.path("/deployments/{deploymentId}/chat/completions", deploymentName).post({ + deploymentId: string, + body: ImageGenerationOptions, + options: GetImageGenerationsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/images/generations", deploymentId).post({ ...operationOptionsToRequestParameters(options), body: { - ...snakeCaseKeys(rest), - tools, - functions, - function_call: functionCall, - messages: messages.map(serializeChatRequestMessage), + model: body["model"], + prompt: body["prompt"], + n: body["n"], + size: body["size"], + response_format: body["responseFormat"], + quality: body["quality"], + style: body["style"], + user: body["user"], }, }); } -export async function _getChatCompletionsWithAzureExtensionsDeserialize(): Promise { - return {} as any; +export async function _getImageGenerationsDeserialize( + result: GetImageGenerations200Response | GetImageGenerationsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw result.body.error; + } + + return { + created: new Date(result.body["created"]), + data: result.body["data"].map((p) => ({ + url: p["url"], + base64Data: p["b64_json"], + revisedPrompt: p["revised_prompt"], + })), + }; } -export async function getChatCompletionsWithAzureExtensions( - _context: Client, - _deploymentId: string, - _body: ChatCompletionsOptions, - _options: ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions = {}, -): Promise { - return {} as any; +/** Creates an image given a prompt. */ +export async function getImageGenerations( + context: Client, + deploymentId: string, + body: ImageGenerationOptions, + options: GetImagesOptions = { requestOptions: {} }, +): Promise { + const result = await _getImageGenerationsSend(context, deploymentId, body, options); + return _getImageGenerationsDeserialize(result); +} + +export function _getEmbeddingsSend( + context: Client, + deploymentId: string, + body: EmbeddingsOptions, + options: GetEmbeddingsOptions = { requestOptions: {} }, +): StreamableMethod { + return context.path("/deployments/{deploymentId}/embeddings", deploymentId).post({ + ...operationOptionsToRequestParameters(options), + body: { user: body["user"], model: body["model"], input: body["input"] }, + }); +} + +export async function _getEmbeddingsDeserialize( + result: GetEmbeddings200Response | GetEmbeddingsDefaultResponse, +): Promise { + if (isUnexpected(result)) { + throw result.body.error; + } + + return { + data: result.body["data"].map((p) => ({ + embedding: p["embedding"], + index: p["index"], + })), + usage: { + promptTokens: result.body.usage["prompt_tokens"], + totalTokens: result.body.usage["total_tokens"], + }, + }; +} + +/** Return the embeddings for a given prompt. */ +export async function getEmbeddings( + context: Client, + deploymentId: string, + body: EmbeddingsOptions, + options: GetEmbeddingsOptions = { requestOptions: {} }, +): Promise { + const result = await _getEmbeddingsSend(context, deploymentId, body, options); + return _getEmbeddingsDeserialize(result); +} + +type ContentFilterResultsForPromptX = { + prompt_filter_results?: Array; + prompt_annotations?: Array; +}; + +function getContentFilterResultsForPrompt({ + prompt_annotations, + prompt_filter_results, +}: ContentFilterResultsForPromptX): ContentFilterResultsForPrompt[] { + const res = prompt_filter_results ?? prompt_annotations; + return ( + res?.map(({ content_filter_results, ...rest }) => ({ + ...camelCaseKeys(rest), + contentFilterResults: parseContentFilterResultDetailsForPromptOutput(content_filter_results), + })) ?? [] + ); +} + +function parseContentFilterResultDetailsForPromptOutput({ + error, + ...rest +}: ContentFilterResultDetailsForPromptOutput = {}): ContentFilterResultDetailsForPrompt { + return error ? parseError(error) : camelCaseKeys(rest); +} + +function parseError(error: ErrorModel): { error: ErrorModel } { + return { + error: { + ...error, + details: error["details"] ?? [], + }, + }; +} + +function parseContentFilterResultsForChoiceOutput({ + error, + ...successResult +}: ContentFilterResultsForChoiceOutput = {}): ContentFilterResultsForChoice { + return error + ? { + error: { + ...error, + details: error["details"] ?? [], + }, + } + : camelCaseKeys(successResult); +} + +function parseMessage(message: ChatResponseMessageOutput): ChatResponseMessage { + const { context, tool_calls, ...rest } = message; + return { + ...camelCaseKeys(rest), + toolCalls: tool_calls ?? [], + ...(!context + ? {} + : { + context: { + ...(!context.messages + ? {} + : { + messages: context.messages.map(parseMessage), + }), + }, + }), + }; } diff --git a/sdk/openai/openai/src/api/policies/nonAzure.ts b/sdk/openai/openai/src/api/policies/nonAzure.ts index 4474d8ab5b63..34944e9d0907 100644 --- a/sdk/openai/openai/src/api/policies/nonAzure.ts +++ b/sdk/openai/openai/src/api/policies/nonAzure.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { PipelinePolicy } from "@azure/core-rest-pipeline"; export function nonAzurePolicy(): PipelinePolicy { diff --git a/sdk/openai/openai/src/api/readableStreamUtils.ts b/sdk/openai/openai/src/api/readableStreamUtils.ts index e69e92e1b7ce..d67982579af3 100644 --- a/sdk/openai/openai/src/api/readableStreamUtils.ts +++ b/sdk/openai/openai/src/api/readableStreamUtils.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - export function polyfillStream(stream: ReadableStream): ReadableStream & AsyncIterable { makeAsyncIterable(stream); return stream; diff --git a/sdk/openai/openai/src/api/util.ts b/sdk/openai/openai/src/api/util.ts index 181477f14b06..83155dc39b04 100644 --- a/sdk/openai/openai/src/api/util.ts +++ b/sdk/openai/openai/src/api/util.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - type CamelCase = S extends `${infer P1}_${infer P2}` ? `${Lowercase}${Capitalize>}` : Lowercase; diff --git a/sdk/openai/openai/src/classic/client/index.ts b/sdk/openai/openai/src/classic/client/index.ts deleted file mode 100644 index 36383a98bd5b..000000000000 --- a/sdk/openai/openai/src/classic/client/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - -import { OpenAIContext } from "../../api/OpenAIContext.js"; -import { - ClientOpenAIClientOperations, - getClientOpenAIClientOperations, -} from "./openAIClient/index.js"; - -export interface ClientOperations { - openAIClient: ClientOpenAIClientOperations; -} - -export function getClientOperations(context: OpenAIContext): ClientOperations { - return { - openAIClient: getClientOpenAIClientOperations(context), - }; -} diff --git a/sdk/openai/openai/src/classic/client/openAIClient/index.ts b/sdk/openai/openai/src/classic/client/openAIClient/index.ts deleted file mode 100644 index 5974aadf4515..000000000000 --- a/sdk/openai/openai/src/classic/client/openAIClient/index.ts +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - -import { OpenAIContext } from "../../../api/OpenAIContext.js"; -import { - AudioTranscriptionOptions, - AudioTranscription, - AudioTranslationOptions, - AudioTranslation, - CompletionsOptions, - Completions, - ChatCompletionsOptions, - ChatCompletions, - ImageGenerationOptions, - ImageGenerations, - EmbeddingsOptions, - Embeddings, -} from "../../../models/models.js"; -import { - getAudioTranscriptionAsPlainText, - getAudioTranscriptionAsResponseObject, - getAudioTranslationAsPlainText, - getAudioTranslationAsResponseObject, - getCompletions, - getChatCompletions, - getChatCompletionsWithAzureExtensions, - getImageGenerations, - getEmbeddings, -} from "../../../api/client/openAIClient/index.js"; -import { - ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ClientOpenAIClientGetCompletionsOptions, - ClientOpenAIClientGetChatCompletionsOptions, - ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ClientOpenAIClientGetImageGenerationsOptions, - ClientOpenAIClientGetEmbeddingsOptions, -} from "../../../models/options.js"; - -export interface ClientOpenAIClientOperations { - getAudioTranscriptionAsPlainText: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ) => Promise; - getAudioTranscriptionAsResponseObject: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ) => Promise; - getAudioTranslationAsPlainText: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ) => Promise; - getAudioTranslationAsResponseObject: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ) => Promise; - getCompletions: ( - deploymentId: string, - body: CompletionsOptions, - options?: ClientOpenAIClientGetCompletionsOptions, - ) => Promise; - getChatCompletions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsOptions, - ) => Promise; - getChatCompletionsWithAzureExtensions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ) => Promise; - getImageGenerations: ( - deploymentId: string, - body: ImageGenerationOptions, - options?: ClientOpenAIClientGetImageGenerationsOptions, - ) => Promise; - getEmbeddings: ( - deploymentId: string, - body: EmbeddingsOptions, - options?: ClientOpenAIClientGetEmbeddingsOptions, - ) => Promise; -} - -export function getClientOpenAIClient(context: OpenAIContext): ClientOpenAIClientOperations { - return { - getAudioTranscriptionAsPlainText: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ) => getAudioTranscriptionAsPlainText(context, deploymentId, body, options), - getAudioTranscriptionAsResponseObject: ( - deploymentId: string, - body: AudioTranscriptionOptions, - options?: ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ) => getAudioTranscriptionAsResponseObject(context, deploymentId, body, options), - getAudioTranslationAsPlainText: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ) => getAudioTranslationAsPlainText(context, deploymentId, body, options), - getAudioTranslationAsResponseObject: ( - deploymentId: string, - body: AudioTranslationOptions, - options?: ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ) => getAudioTranslationAsResponseObject(context, deploymentId, body, options), - getCompletions: ( - deploymentId: string, - body: CompletionsOptions, - options?: ClientOpenAIClientGetCompletionsOptions, - ) => getCompletions(context, deploymentId, body.prompt, { ...body, ...options }), - getChatCompletions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsOptions, - ) => getChatCompletions(context, deploymentId, body.messages, { ...body, ...options }), - getChatCompletionsWithAzureExtensions: ( - deploymentId: string, - body: ChatCompletionsOptions, - options?: ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ) => getChatCompletionsWithAzureExtensions(context, deploymentId, body, options), - getImageGenerations: ( - deploymentId: string, - body: ImageGenerationOptions, - options?: ClientOpenAIClientGetImageGenerationsOptions, - ) => getImageGenerations(context, deploymentId, body, options), - getEmbeddings: ( - deploymentId: string, - body: EmbeddingsOptions, - options?: ClientOpenAIClientGetEmbeddingsOptions, - ) => getEmbeddings(context, deploymentId, body, options), - }; -} - -export function getClientOpenAIClientOperations( - context: OpenAIContext, -): ClientOpenAIClientOperations { - return { - ...getClientOpenAIClient(context), - }; -} diff --git a/sdk/openai/openai/src/classic/index.ts b/sdk/openai/openai/src/classic/index.ts deleted file mode 100644 index f11a2dc32934..000000000000 --- a/sdk/openai/openai/src/classic/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - -export { ClientOperations } from "./client/index.js"; -export { ClientOpenAIClientOperations } from "./client/openAIClient/index.js"; diff --git a/sdk/openai/openai/src/index.ts b/sdk/openai/openai/src/index.ts index 29a0513173cc..e8cfca9c390c 100644 --- a/sdk/openai/openai/src/index.ts +++ b/sdk/openai/openai/src/index.ts @@ -17,101 +17,110 @@ export { OpenAIClient, OpenAIClientOptions } from "./OpenAIClient.js"; export { OpenAIKeyCredential } from "./OpenAIKeyCredential.js"; export * from "./models/audio.js"; export { - AzureChatEnhancementConfiguration, - AzureChatEnhancements, - AzureChatExtensionType, - AzureChatExtensionsMessageContext, - AzureChatGroundingEnhancementConfiguration, - AzureChatOCREnhancementConfiguration, - AzureCognitiveSearchIndexFieldMappingOptions, - AzureCognitiveSearchQueryType, - AzureCosmosDBFieldMappingOptions, - AzureGroundingEnhancement, - AzureGroundingEnhancementCoordinatePoint, - AzureGroundingEnhancementLine, - AzureGroundingEnhancementLineSpan, - ChatCompletionsNamedToolSelection, - ChatCompletionsResponseFormat, - ChatCompletionsToolDefinition, - ChatFinishDetails, - ChatMessageContentItem, - ChatMessageImageDetailLevel, - ChatMessageImageUrl, - ChatResponseMessage, - ChatRole, - CompletionsFinishReason, - CompletionsLogProbabilityModel, - CompletionsUsage, - ContentFilterBlocklistIdResult, - ContentFilterCitedDetectionResult, - ContentFilterDetectionResult, - ContentFilterSeverity, - ContentFilterResult, - ElasticsearchIndexFieldMappingOptions, - ElasticsearchQueryType, - EmbeddingItem, - Embeddings, - EmbeddingsUsage, - FunctionCall, - FunctionCallPreset, - FunctionDefinition, - FunctionName, - ImageGenerationData, - ImageGenerationQuality, - ImageGenerationResponseFormat, - ImageGenerationStyle, - ImageGenerations, - ImageSize, - OnYourDataAuthenticationOptions, - OnYourDataAuthenticationType, - OnYourDataVectorizationSource, - OnYourDataVectorizationSourceType, - PineconeFieldMappingOptions, - ChatChoice, - ChatCompletions, - Choice, + AzureExtensionsOptions, Completions, + ContentFilterResultsForPrompt, ContentFilterResultDetailsForPrompt, + ContentFilterResult, + ContentFilterSeverity, + ContentFilterDetectionResult, + ContentFilterBlocklistIdResult, + Choice, ContentFilterResultsForChoice, - ContentFilterResultsForPrompt, - ContentFilterErrorResults, ContentFilterSuccessResultDetailsForPrompt, + ContentFilterErrorResults, ContentFilterSuccessResultsForChoice, - ChatRequestAssistantMessage, - ChatRequestFunctionMessage, + ContentFilterCitedDetectionResult, + CompletionsLogProbabilityModel, + CompletionsFinishReason, + CompletionsUsage, ChatRequestMessage, ChatRequestSystemMessage, - ChatRequestToolMessage, ChatRequestUserMessage, - ChatCompletionsFunctionToolCall, + ChatMessageContentItem, + ChatMessageTextContentItem, + ChatMessageImageContentItem, + ChatMessageImageUrl, + ChatMessageImageDetailLevel, + ChatRequestAssistantMessage, ChatCompletionsToolCall, - MaxTokensFinishDetails, - StopFinishDetails, - GetCompletionsOptions, - GetEmbeddingsOptions, - GetImagesOptions, - AzureExtensionsOptions, - GetChatCompletionsOptions, + ChatCompletionsFunctionToolCall, + FunctionCall, + ChatRequestToolMessage, + ChatRequestFunctionMessage, + ChatRole, + FunctionDefinition, + FunctionCallPreset, + FunctionName, AzureChatExtensionConfiguration, AzureCognitiveSearchChatExtensionConfiguration, - AzureCosmosDBChatExtensionConfiguration, - AzureMachineLearningIndexChatExtensionConfiguration, - ElasticsearchChatExtensionConfiguration, - PineconeChatExtensionConfiguration, - ChatCompletionsNamedFunctionToolSelection, - ChatMessageTextContentItem, - ChatCompletionsFunctionToolDefinition, - ChatMessageImageContentItem, - ChatCompletionsToolSelectionPreset, + OnYourDataAuthenticationOptions, OnYourDataApiKeyAuthenticationOptions, OnYourDataConnectionStringAuthenticationOptions, - OnYourDataDeploymentNameVectorizationSource, - OnYourDataEndpointVectorizationSource, OnYourDataKeyAndKeyIdAuthenticationOptions, - OnYourDataModelIdVectorizationSource, OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, OnYourDataUserAssignedManagedIdentityAuthenticationOptions, + OnYourDataAuthenticationType, + AzureCognitiveSearchIndexFieldMappingOptions, + AzureCognitiveSearchQueryType, + OnYourDataVectorizationSource, + OnYourDataEndpointVectorizationSource, + OnYourDataDeploymentNameVectorizationSource, + OnYourDataModelIdVectorizationSource, + OnYourDataVectorizationSourceType, + AzureMachineLearningIndexChatExtensionConfiguration, + AzureCosmosDBChatExtensionConfiguration, + AzureCosmosDBFieldMappingOptions, + ElasticsearchChatExtensionConfiguration, + ElasticsearchIndexFieldMappingOptions, + ElasticsearchQueryType, + PineconeChatExtensionConfiguration, + PineconeFieldMappingOptions, + AzureChatExtensionType, + AzureChatEnhancementConfiguration, + AzureChatGroundingEnhancementConfiguration, + AzureChatOCREnhancementConfiguration, + ChatCompletionsResponseFormat, ChatCompletionsTextResponseFormat, ChatCompletionsJsonResponseFormat, + ChatCompletionsToolDefinition, + ChatCompletionsFunctionToolDefinition, + ChatCompletionsToolSelectionPreset, + ChatCompletionsNamedToolSelection, + ChatCompletionsNamedFunctionToolSelection, + ChatCompletions, + ChatChoice, + ChatResponseMessage, + AzureChatExtensionsMessageContext, + ChatFinishDetails, + StopFinishDetails, + MaxTokensFinishDetails, + AzureChatEnhancements, + AzureGroundingEnhancement, + AzureGroundingEnhancementLine, + AzureGroundingEnhancementLineSpan, + AzureGroundingEnhancementCoordinatePoint, + ImageSize, + ImageGenerationResponseFormat, + ImageGenerationQuality, + ImageGenerationStyle, + ImageGenerations, + ImageGenerationData, + Embeddings, + EmbeddingItem, + EmbeddingsUsage, + ChatRequestMessageUnion, + ChatMessageContentItemUnion, + ChatCompletionsToolCallUnion, + OnYourDataAuthenticationOptionsUnion, + OnYourDataVectorizationSourceUnion, + ChatCompletionsResponseFormatUnion, + ChatCompletionsToolDefinitionUnion, + ChatCompletionsNamedToolSelectionUnion, + ChatFinishDetailsUnion, + GetCompletionsOptions, + GetChatCompletionsOptions, + GetImagesOptions, + GetEmbeddingsOptions, EventStream, } from "./models/index.js"; diff --git a/sdk/openai/openai/src/logger.ts b/sdk/openai/openai/src/logger.ts index d4a87df1300f..5679314738ce 100644 --- a/sdk/openai/openai/src/logger.ts +++ b/sdk/openai/openai/src/logger.ts @@ -1,13 +1,5 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { createClientLogger } from "@azure/logger"; export const logger = createClientLogger("openai"); diff --git a/sdk/openai/openai/src/models/index.ts b/sdk/openai/openai/src/models/index.ts index e35844308892..498d59b77d8c 100644 --- a/sdk/openai/openai/src/models/index.ts +++ b/sdk/openai/openai/src/models/index.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - export { AudioTranscriptionOptions, AudioTranscriptionFormat, @@ -19,8 +11,12 @@ export { AudioTranslationFormat, AudioTranslation, AudioTranslationSegment, + AzureExtensionsOptions, CompletionsOptions, Completions, + ContentFilterErrorResults, + ContentFilterSuccessResultDetailsForPrompt, + ContentFilterSuccessResultsForChoice, ContentFilterResultsForPrompt, ContentFilterResultDetailsForPrompt, ContentFilterResult, @@ -33,39 +29,67 @@ export { CompletionsLogProbabilityModel, CompletionsFinishReason, CompletionsUsage, - ChatCompletionsOptions, ChatRequestMessage, - ChatRole, + ChatRequestSystemMessage, + ChatRequestUserMessage, ChatMessageContentItem, + ChatMessageTextContentItem, + ChatMessageImageContentItem, ChatMessageImageUrl, ChatMessageImageDetailLevel, + ChatRequestAssistantMessage, ChatCompletionsToolCall, + ChatCompletionsFunctionToolCall, FunctionCall, + ChatRequestToolMessage, + ChatRequestFunctionMessage, + ChatRole, FunctionDefinition, FunctionCallPreset, FunctionName, - AzureChatExtensionType, + AzureChatExtensionConfiguration, + AzureCognitiveSearchChatExtensionConfiguration, OnYourDataAuthenticationOptions, + OnYourDataApiKeyAuthenticationOptions, + OnYourDataConnectionStringAuthenticationOptions, + OnYourDataKeyAndKeyIdAuthenticationOptions, + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, + OnYourDataUserAssignedManagedIdentityAuthenticationOptions, OnYourDataAuthenticationType, AzureCognitiveSearchIndexFieldMappingOptions, AzureCognitiveSearchQueryType, OnYourDataVectorizationSource, + OnYourDataEndpointVectorizationSource, + OnYourDataDeploymentNameVectorizationSource, + OnYourDataModelIdVectorizationSource, OnYourDataVectorizationSourceType, + AzureMachineLearningIndexChatExtensionConfiguration, + AzureCosmosDBChatExtensionConfiguration, AzureCosmosDBFieldMappingOptions, + ElasticsearchChatExtensionConfiguration, ElasticsearchIndexFieldMappingOptions, ElasticsearchQueryType, + PineconeChatExtensionConfiguration, PineconeFieldMappingOptions, + AzureChatExtensionType, AzureChatEnhancementConfiguration, AzureChatGroundingEnhancementConfiguration, AzureChatOCREnhancementConfiguration, ChatCompletionsResponseFormat, + ChatCompletionsTextResponseFormat, + ChatCompletionsJsonResponseFormat, ChatCompletionsToolDefinition, + ChatCompletionsFunctionToolDefinition, + ChatCompletionsToolSelectionPreset, ChatCompletionsNamedToolSelection, + ChatCompletionsNamedFunctionToolSelection, ChatCompletions, ChatChoice, ChatResponseMessage, AzureChatExtensionsMessageContext, ChatFinishDetails, + StopFinishDetails, + MaxTokensFinishDetails, AzureChatEnhancements, AzureGroundingEnhancement, AzureGroundingEnhancementLine, @@ -82,53 +106,26 @@ export { Embeddings, EmbeddingItem, EmbeddingsUsage, - ContentFilterErrorResults, - ContentFilterSuccessResultDetailsForPrompt, - ContentFilterSuccessResultsForChoice, - ChatRequestAssistantMessage, - ChatRequestFunctionMessage, - ChatRequestSystemMessage, - ChatRequestToolMessage, - ChatRequestUserMessage, - ChatCompletionsFunctionToolCall, - MaxTokensFinishDetails, - StopFinishDetails, - AzureChatExtensionConfiguration, - AzureCognitiveSearchChatExtensionConfiguration, - AzureCosmosDBChatExtensionConfiguration, - AzureExtensionsOptions, - AzureMachineLearningIndexChatExtensionConfiguration, - ElasticsearchChatExtensionConfiguration, - PineconeChatExtensionConfiguration, - ChatCompletionsNamedFunctionToolSelection, - ChatMessageTextContentItem, - ChatCompletionsFunctionToolDefinition, - ChatMessageImageContentItem, - ChatCompletionsToolSelectionPreset, - OnYourDataApiKeyAuthenticationOptions, - OnYourDataConnectionStringAuthenticationOptions, - OnYourDataDeploymentNameVectorizationSource, - OnYourDataEndpointVectorizationSource, - OnYourDataKeyAndKeyIdAuthenticationOptions, - OnYourDataModelIdVectorizationSource, - OnYourDataSystemAssignedManagedIdentityAuthenticationOptions, - OnYourDataUserAssignedManagedIdentityAuthenticationOptions, - ChatCompletionsTextResponseFormat, - ChatCompletionsJsonResponseFormat, EventStream, + ChatRequestMessageUnion, + ChatMessageContentItemUnion, + ChatCompletionsToolCallUnion, + OnYourDataAuthenticationOptionsUnion, + OnYourDataVectorizationSourceUnion, + ChatCompletionsResponseFormatUnion, + ChatCompletionsToolDefinitionUnion, + ChatCompletionsNamedToolSelectionUnion, + ChatFinishDetailsUnion, } from "./models.js"; export { - ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions, - ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions, - ClientOpenAIClientGetAudioTranslationAsPlainTextOptions, - ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions, - ClientOpenAIClientGetCompletionsOptions, - ClientOpenAIClientGetChatCompletionsOptions, - ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions, - ClientOpenAIClientGetImageGenerationsOptions, - ClientOpenAIClientGetEmbeddingsOptions, + GetAudioTranscriptionAsPlainTextOptions, + GetAudioTranscriptionAsResponseObjectOptions, + GetAudioTranslationAsPlainTextOptions, + GetAudioTranslationAsResponseObjectOptions, GetCompletionsOptions, - GetEmbeddingsOptions, GetImagesOptions, + GetImageGenerationsOptions, GetChatCompletionsOptions, + GetChatCompletionsWithAzureExtensionsOptions, + GetEmbeddingsOptions, } from "./options.js"; diff --git a/sdk/openai/openai/src/models/models.ts b/sdk/openai/openai/src/models/models.ts index 647feb0ec7f7..1cb2b3449ae4 100644 --- a/sdk/openai/openai/src/models/models.ts +++ b/sdk/openai/openai/src/models/models.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { ErrorModel } from "@azure-rest/core-client"; /** The configuration information for an audio transcription request. */ @@ -43,6 +35,10 @@ export interface AudioTranscriptionOptions { model?: string; } +/** Defines available options for the underlying response format of output transcription information. */ +/** "json", "verbose_json", "text", "srt", "vtt" */ +export type AudioTranscriptionFormat = string; + /** Result information for an operation that transcribed spoken audio into written text. */ export interface AudioTranscription { /** The transcribed text for the provided audio data. */ @@ -60,6 +56,10 @@ export interface AudioTranscription { segments?: AudioTranscriptionSegment[]; } +/** Defines the possible descriptors for available audio operation responses. */ +/** "transcribe", "translate" */ +export type AudioTaskLabel = string; + /** * Extended information about a single segment of transcribed audio data. * Segments generally represent roughly 5-10 seconds of speech. Segment boundaries typically occur between words but not @@ -120,6 +120,10 @@ export interface AudioTranslationOptions { model?: string; } +/** Defines available options for the underlying response format of output translation information. */ +/** "json", "verbose_json", "text", "srt", "vtt" */ +export type AudioTranslationFormat = string; + /** Result information for an operation that translated spoken audio into written text. */ export interface AudioTranslation { /** The translated text for the provided audio data. */ @@ -136,6 +140,18 @@ export interface AudioTranslation { /** A collection of information about the timing, probabilities, and other detail of each processed audio segment. */ segments?: AudioTranslationSegment[]; } +/** + * Options for Azure OpenAI chat extensions. + */ +export interface AzureExtensionsOptions { + /** + * The configuration entries for Azure OpenAI chat extensions that use them. + * This additional specification is only compatible with Azure OpenAI. + */ + extensions?: AzureChatExtensionConfiguration[]; + /** If provided, the configuration options for available Azure OpenAI chat enhancements. */ + enhancements?: AzureChatEnhancementConfiguration; +} /** * Extended information about a single segment of translated audio data. @@ -250,7 +266,7 @@ export interface CompletionsOptions { * When used together with n, bestOf controls the number of candidate completions and must be * greater than n. * Because this setting can generate many completions, it may quickly consume your token quota. - * Use carefully and ensure reasonable settings for maxTokens and stop. + * Use carefully and ensure reasonable settings for max_tokens and stop. */ bestOf?: number; /** A value indicating whether chat completions should be streamed for this request. */ @@ -263,6 +279,95 @@ export interface CompletionsOptions { model?: string; } +/** + * Representation of the response data from a completions request. + * Completions support a wide variety of tasks and generate text that continues from or "completes" + * provided prompt data. + */ +export interface Completions { + /** A unique identifier associated with this completions response. */ + id: string; + /** + * The first timestamp associated with generation activity for this completions response, + * represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. + */ + created: Date; + /** + * Content filtering results for zero or more prompts in the request. In a streaming request, + * results for different prompts may arrive at different times or in different orders. + */ + promptFilterResults: ContentFilterResultsForPrompt[]; + /** + * The collection of completions choices associated with this completions response. + * Generally, `n` choices are generated per provided prompt with a default value of 1. + * Token limits and other settings may limit the number of choices generated. + */ + choices: Choice[]; + /** Usage information for tokens processed and generated as part of this completions operation. */ + usage: CompletionsUsage; +} + +/** Content filtering results for a single prompt in the request. */ +export interface ContentFilterResultsForPrompt { + /** The index of this prompt in the set of prompt results */ + promptIndex: number; + /** Content filtering results for this prompt */ + contentFilterResults: ContentFilterResultDetailsForPrompt; +} + +/** Information about the content filtering category, if it has been detected. */ +export type ContentFilterResultDetailsForPrompt = + | ContentFilterSuccessResultDetailsForPrompt + | ContentFilterErrorResults; +/** Information about the content filtering success result. */ +export interface ContentFilterSuccessResultDetailsForPrompt { + /** + * Describes language related to anatomical organs and genitals, romantic relationships, + * acts portrayed in erotic or affectionate terms, physical sexual acts, including + * those portrayed as an assault or a forced sexual violent act against one’s will, + * prostitution, pornography, and abuse. + */ + sexual?: ContentFilterResult; + /** + * Describes language related to physical actions intended to hurt, injure, damage, or + * kill someone or something; describes weapons, etc. + */ + violence?: ContentFilterResult; + /** + * Describes language attacks or uses that include pejorative or discriminatory language + * with reference to a person or identity group on the basis of certain differentiating + * attributes of these groups including but not limited to race, ethnicity, nationality, + * gender identity and expression, sexual orientation, religion, immigration status, ability + * status, personal appearance, and body size. + */ + hate?: ContentFilterResult; + /** + * Describes language related to physical actions intended to purposely hurt, injure, + * or damage one’s body, or kill oneself. + */ + selfHarm?: ContentFilterResult; + /** + * Describes an error returned if the content filtering system is + * down or otherwise unable to complete the operation in time. + */ + error?: undefined; + /** Describes whether profanity was detected. */ + profanity?: ContentFilterDetectionResult; + /** Describes detection results against configured custom blocklists. */ + customBlocklists?: ContentFilterBlocklistIdResult[]; + /** Whether a jailbreak attempt was detected in the prompt. */ + jailbreak?: ContentFilterDetectionResult; +} + +/** Information about the content filtering error result. */ +export interface ContentFilterErrorResults { + /** + * Describes an error returned if the content filtering system is + * down or otherwise unable to complete the operation in time. + */ + error: ErrorModel; +} + /** Information about filtered content severity level and if it has been filtered or not. */ export interface ContentFilterResult { /** Ratings for the intensity and risk level of filtered content. */ @@ -271,6 +376,10 @@ export interface ContentFilterResult { filtered: boolean; } +/** Ratings for the intensity and risk level of harmful content. */ +/** "safe", "low", "medium", "high" */ +export type ContentFilterSeverity = string; + /** Represents the outcome of a detection operation performed by content filtering. */ export interface ContentFilterDetectionResult { /** A value indicating whether or not the content has been filtered. */ @@ -287,6 +396,75 @@ export interface ContentFilterBlocklistIdResult { filtered: boolean; } +/** + * The representation of a single prompt completion as part of an overall completions request. + * Generally, `n` choices are generated per provided prompt with a default value of 1. + * Token limits and other settings may limit the number of choices generated. + */ +export interface Choice { + /** The generated text for a given completions prompt. */ + text: string; + /** The ordered index associated with this completions choice. */ + index: number; + /** + * Information about the content filtering category (hate, sexual, violence, self_harm), if it + * has been detected, as well as the severity level (very_low, low, medium, high-scale that + * determines the intensity and risk level of harmful content) and if it has been filtered or not. + */ + contentFilterResults?: ContentFilterResultsForChoice; + /** The log probabilities model for tokens associated with this completions choice. */ + logprobs: CompletionsLogProbabilityModel | null; + /** Reason for finishing */ + finishReason: CompletionsFinishReason | null; +} + +/** Information about the content filtering results, if it has been detected. */ +export type ContentFilterResultsForChoice = + | ContentFilterSuccessResultsForChoice + | ContentFilterErrorResults; + +/** Information about content filtering evaluated against generated model output. */ +export interface ContentFilterSuccessResultsForChoice { + /** + * Describes language related to anatomical organs and genitals, romantic relationships, + * acts portrayed in erotic or affectionate terms, physical sexual acts, including + * those portrayed as an assault or a forced sexual violent act against one’s will, + * prostitution, pornography, and abuse. + */ + sexual?: ContentFilterResult; + /** + * Describes language related to physical actions intended to hurt, injure, damage, or + * kill someone or something; describes weapons, etc. + */ + violence?: ContentFilterResult; + /** + * Describes language attacks or uses that include pejorative or discriminatory language + * with reference to a person or identity group on the basis of certain differentiating + * attributes of these groups including but not limited to race, ethnicity, nationality, + * gender identity and expression, sexual orientation, religion, immigration status, ability + * status, personal appearance, and body size. + */ + hate?: ContentFilterResult; + /** + * Describes language related to physical actions intended to purposely hurt, injure, + * or damage one’s body, or kill oneself. + */ + selfHarm?: ContentFilterResult; + /** Describes whether profanity was detected. */ + profanity?: ContentFilterDetectionResult; + /** Describes detection results against configured custom blocklists. */ + customBlocklists?: ContentFilterBlocklistIdResult[]; + /** + * Describes an error returned if the content filtering system is + * down or otherwise unable to complete the operation in time. + */ + error?: undefined; + /** Information about detection of protected text material. */ + protectedMaterialText?: ContentFilterDetectionResult; + /** Information about detection of protected code material. */ + protectedMaterialCode?: ContentFilterCitedDetectionResult; +} + /** Represents the outcome of a detection operation against protected resources as performed by content filtering. */ export interface ContentFilterCitedDetectionResult { /** A value indicating whether or not the content has been filtered. */ @@ -323,9 +501,13 @@ export interface CompletionsLogProbabilityModel { textOffset: number[]; } +/** Representation of the manner in which a completions response concluded. */ +/** "stop", "length", "content_filter", "function_call", "tool_calls" */ +export type CompletionsFinishReason = string; + /** * Representation of the token counts processed for a completions request. - * Counts consider all tokens across prompts, choices, choice alternates, bestOf generations, and + * Counts consider all tokens across prompts, choices, choice alternates, best_of generations, and * other consumers. */ export interface CompletionsUsage { @@ -349,7 +531,7 @@ export interface ChatCompletionsOptions { * the behavior of the assistant, followed by alternating messages between the User and * Assistant roles. */ - messages: ChatRequestMessage[]; + messages: ChatRequestMessageUnion[]; /** A list of functions the model may generate JSON inputs for. */ functions?: FunctionDefinition[]; /** @@ -365,7 +547,7 @@ export interface ChatCompletionsOptions { * The sampling temperature to use that controls the apparent creativity of generated completions. * Higher values will make output more random while lower values will make results more focused * and deterministic. - * It is not recommended to modify temperature and topP for the same completions request as the + * It is not recommended to modify temperature and top_p for the same completions request as the * interaction of these two settings is difficult to predict. */ temperature?: number; @@ -374,7 +556,7 @@ export interface ChatCompletionsOptions { * model to consider the results of tokens with the provided probability mass. As an example, a * value of 0.15 will cause only the tokens comprising the top 15% of probability mass to be * considered. - * It is not recommended to modify temperature and topP for the same completions request as the + * It is not recommended to modify temperature and top_p for the same completions request as the * interaction of these two settings is difficult to predict. */ topP?: number; @@ -395,7 +577,7 @@ export interface ChatCompletionsOptions { * The number of chat completions choices that should be generated for a chat completions * response. * Because this setting can generate many completions, it may quickly consume your token quota. - * Use carefully and ensure reasonable settings for maxTokens and stop. + * Use carefully and ensure reasonable settings for max_tokens and stop. */ n?: number; /** A collection of textual sequences that will end completions generation. */ @@ -432,22 +614,54 @@ export interface ChatCompletionsOptions { /** * If specified, the system will make a best effort to sample deterministically such that repeated requests with the * same seed and parameters should return the same result. Determinism is not guaranteed, and you should refer to the - * systemFingerprint response parameter to monitor changes in the backend." + * system_fingerprint response parameter to monitor changes in the backend." */ seed?: number; /** An object specifying the format that the model must output. Used to enable JSON mode. */ - responseFormat?: ChatCompletionsResponseFormat; + responseFormat?: ChatCompletionsResponseFormatUnion; /** The available tool definitions that the chat completions request can use, including caller-defined functions. */ - tools?: ChatCompletionsToolDefinition[]; + tools?: ChatCompletionsToolDefinitionUnion[]; /** If specified, the model will configure which of the provided tools it can use for the chat completions response. */ - toolChoice?: ChatCompletionsNamedToolSelection; + toolChoice?: ChatCompletionsToolSelectionPreset | ChatCompletionsNamedToolSelectionUnion; +} + +/** An abstract representation of a chat message as provided in a request. */ +export interface ChatRequestMessage { + /** the discriminator possible values: system, user, assistant, tool, function */ + role: ChatRole; +} + +/** + * A request chat message containing system instructions that influence how the model will generate a chat completions + * response. + */ +export interface ChatRequestSystemMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'system' for system messages. */ + role: "system"; + /** The contents of the system message. */ + content: string; + /** An optional name for the participant. */ + name?: string; +} + +/** A request chat message representing user input to the assistant. */ +export interface ChatRequestUserMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'user' for user messages. */ + role: "user"; + /** The contents of the user message, with available input types varying by selected model. */ + content: string | ChatMessageContentItemUnion[]; + /** An optional name for the participant. */ + name?: string; } -/** A representation of a structured content item within a chat message. */ -export type ChatMessageContentItem = ChatMessageTextContentItem | ChatMessageImageContentItem; +/** An abstract representation of a structured content item within a chat message. */ +export interface ChatMessageContentItem { + /** the discriminator possible values: text, image_url */ + type: string; +} /** A structured chat content item containing plain text. */ -export interface ChatMessageTextContentItem { +export interface ChatMessageTextContentItem extends ChatMessageContentItem { /** The discriminated object type: always 'text' for this type. */ type: "text"; /** The content of the message. */ @@ -455,7 +669,7 @@ export interface ChatMessageTextContentItem { } /** A structured chat content item containing an image reference. */ -export interface ChatMessageImageContentItem { +export interface ChatMessageImageContentItem extends ChatMessageContentItem { /** The discriminated object type: always 'image_url' for this type. */ type: "image_url"; /** An internet location, which must be accessible to the model,from which the image may be retrieved. */ @@ -469,25 +683,41 @@ export interface ChatMessageImageUrl { /** * The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and * accuracy. - * - * Possible values: auto, low, high */ detail?: ChatMessageImageDetailLevel; } /** A representation of the possible image detail levels for image-based chat completions message content. */ /** "auto", "low", "high" */ -export type ChatMessageImageDetailLevel = "auto" | "low" | "high"; +export type ChatMessageImageDetailLevel = string; + +/** A request chat message representing response or action from the assistant. */ +export interface ChatRequestAssistantMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'assistant' for assistant messages. */ + role: "assistant"; + /** The content of the message. */ + content: string | null; + /** An optional name for the participant. */ + name?: string; + /** + * The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat + * completions request to resolve as configured. + */ + toolCalls?: ChatCompletionsToolCallUnion[]; + /** + * The function call that must be resolved and have its output appended to subsequent input messages for the chat + * completions request to resolve as configured. + */ + functionCall?: FunctionCall; +} /** - * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents - * a function invocation needed for a subsequent chat completions request to resolve. + * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested + * chat completion. */ -export interface ChatCompletionsFunctionToolCall { - /** The type of tool call, in this case always 'function'. */ - type: "function"; - /** The details of the function invocation requested by the tool call. */ - function: FunctionCall; +export interface ChatCompletionsToolCall { + /** the discriminator possible values: function */ + type: string; /** The ID of the tool call. */ id: string; /** The index of the tool call. */ @@ -495,14 +725,19 @@ export interface ChatCompletionsFunctionToolCall { } /** - * A representation of a tool call that must be resolved in a subsequent request to perform the requested - * chat completion. + * A tool call to a function tool, issued by the model in evaluation of a configured function tool, that represents + * a function invocation needed for a subsequent chat completions request to resolve. */ -export type ChatCompletionsToolCall = ChatCompletionsFunctionToolCall; - -/** The name and arguments of a function that should be called, as generated by the model. */ -export interface FunctionCall { - /** The name of the function to call. */ +export interface ChatCompletionsFunctionToolCall extends ChatCompletionsToolCall { + /** The type of tool call, in this case always 'function'. */ + type: "function"; + /** The details of the function invocation requested by the tool call. */ + function: FunctionCall; +} + +/** The name and arguments of a function that should be called, as generated by the model. */ +export interface FunctionCall { + /** The name of the function to call. */ name: string; /** * The arguments to call the function with, as generated by the model in JSON format. @@ -513,6 +748,30 @@ export interface FunctionCall { arguments: string; } +/** A request chat message representing requested output from a configured tool. */ +export interface ChatRequestToolMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'tool' for tool messages. */ + role: "tool"; + /** The content of the message. */ + content: string | null; + /** The ID of the tool call resolved by the provided content. */ + toolCallId: string; +} + +/** A request chat message representing requested output from a configured function. */ +export interface ChatRequestFunctionMessage extends ChatRequestMessage { + /** The chat role associated with this message, which is always 'function' for function messages. */ + role: "function"; + /** The name of the function that was called to produce output. */ + name: string; + /** The output of the function as requested by the function call. */ + content: string | null; +} + +/** A description of the intended purpose of a message within a chat completions interaction. */ +/** "system", "assistant", "user", "function", "tool" */ +export type ChatRole = string; + /** The definition of a caller-specified function that chat completions may invoke in response to matching user input. */ export interface FunctionDefinition { /** The name of the function to be called. */ @@ -522,10 +781,17 @@ export interface FunctionDefinition { * interpreting its parameters. */ description?: string; - /** The parameters the functions accepts, described as a JSON Schema object. */ + /** The parameters the function accepts, described as a JSON Schema object. */ parameters?: Record; } +/** + * The collection of predefined behaviors for handling request-provided function information in a chat completions + * operation. + */ +/** "auto", "none" */ +export type FunctionCallPreset = string; + /** * A structure that specifies the exact name of a specific, request-provided function to use when processing a chat * completions operation. @@ -535,48 +801,110 @@ export interface FunctionName { name: string; } -/** Optional settings to control how fields are processed when using a configured Azure Cognitive Search resource. */ -export interface AzureCognitiveSearchIndexFieldMappingOptions { - /** The name of the index field to use as a title. */ - titleField?: string; - /** The name of the index field to use as a URL. */ - urlField?: string; - /** The name of the index field to use as a filepath. */ - filepathField?: string; - /** The names of index fields that should be treated as content. */ - contentFields?: string[]; - /** The separator pattern that content fields should use. */ - contentFieldsSeparator?: string; - /** The names of fields that represent vector data. */ - vectorFields?: string[]; - /** The names of fields that represent image vector data. */ - imageVectorFields?: string[]; +/** + * A specific representation of configurable options for Azure Cognitive Search when using it as an Azure OpenAI chat + * extension. + */ +export interface AzureCognitiveSearchChatExtensionConfiguration { + /** + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Azure Cognitive Search. + */ + type: "AzureCognitiveSearch"; + /** + * The authentication method to use when accessing the defined data source. + * Each data source type supports a specific set of available authentication methods; please see the documentation of + * the data source for supported mechanisms. + * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + * authentication. + */ + authentication?: OnYourDataAuthenticationOptionsUnion; + /** The configured top number of documents to feature for the configured query. */ + topNDocuments?: number; + /** Whether queries should be restricted to use of indexed data. */ + inScope?: boolean; + /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ + strictness?: number; + /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ + roleInformation?: string; + /** The absolute endpoint path for the Azure Cognitive Search resource to use. */ + endpoint: string; + /** The name of the index to use as available in the referenced Azure Cognitive Search resource. */ + indexName: string; + /** The API key to use when interacting with the Azure Cognitive Search resource. */ + key?: string; + /** Customized field mapping behavior to use when interacting with the search index. */ + fieldsMapping?: AzureCognitiveSearchIndexFieldMappingOptions; + /** The query type to use with Azure Cognitive Search. */ + queryType?: AzureCognitiveSearchQueryType; + /** The additional semantic configuration for the query. */ + semanticConfiguration?: string; + /** Search filter. */ + filter?: string; + /** When using embeddings for search, specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of format `https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings?api-version={api-version}`. */ + embeddingEndpoint?: string; + /** When using embeddings, specifies the API key to use with the provided embeddings endpoint. */ + embeddingKey?: string; + /** The embedding dependency for vector search. */ + embeddingDependency?: OnYourDataVectorizationSourceUnion; } -/** Optional settings to control how fields are processed when using a configured Azure Cosmos DB resource. */ -export interface AzureCosmosDBFieldMappingOptions { - /** The names of fields that represent vector data. */ - vectorFields: string[]; +/** The authentication options for Azure OpenAI On Your Data. */ +export interface OnYourDataAuthenticationOptions { + /** the discriminator possible values: APIKey, ConnectionString, KeyAndKeyId, SystemAssignedManagedIdentity, UserAssignedManagedIdentity */ + type: OnYourDataAuthenticationType; } -/** Optional settings to control how fields are processed when using a configured Elasticsearch® resource. */ -export interface ElasticsearchIndexFieldMappingOptions { - /** The name of the index field to use as a title. */ - titleField?: string; - /** The name of the index field to use as a URL. */ - urlField?: string; - /** The name of the index field to use as a filepath. */ - filepathField?: string; - /** The names of index fields that should be treated as content. */ - contentFields?: string[]; - /** The separator pattern that content fields should use. */ - contentFieldsSeparator?: string; - /** The names of fields that represent vector data. */ - vectorFields?: string[]; +/** The authentication options for Azure OpenAI On Your Data when using an API key. */ +export interface OnYourDataApiKeyAuthenticationOptions extends OnYourDataAuthenticationOptions { + /** The authentication type of API key. */ + type: "APIKey"; + /** The API key to use for authentication. */ + key: string; } -/** Optional settings to control how fields are processed when using a configured Pinecone resource. */ -export interface PineconeFieldMappingOptions { +/** The authentication options for Azure OpenAI On Your Data when using a connection string. */ +export interface OnYourDataConnectionStringAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of connection string. */ + type: "ConnectionString"; + /** The connection string to use for authentication. */ + connectionString: string; +} + +/** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. */ +export interface OnYourDataKeyAndKeyIdAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of Elasticsearch key and key ID pair. */ + type: "KeyAndKeyId"; + /** The key to use for authentication. */ + key: string; + /** The key ID to use for authentication. */ + keyId: string; +} + +/** The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. */ +export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of system-assigned managed identity. */ + type: "SystemAssignedManagedIdentity"; +} + +/** The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. */ +export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions + extends OnYourDataAuthenticationOptions { + /** The authentication type of user-assigned managed identity. */ + type: "UserAssignedManagedIdentity"; + /** The resource ID of the user-assigned managed identity to use for authentication. */ + managedIdentityResourceId: string; +} + +/** The authentication types supported with Azure OpenAI On Your Data. */ +/** "APIKey", "ConnectionString", "KeyAndKeyId", "SystemAssignedManagedIdentity", "UserAssignedManagedIdentity" */ +export type OnYourDataAuthenticationType = string; + +/** Optional settings to control how fields are processed when using a configured Azure Cognitive Search resource. */ +export interface AzureCognitiveSearchIndexFieldMappingOptions { /** The name of the index field to use as a title. */ titleField?: string; /** The name of the index field to use as a URL. */ @@ -593,303 +921,262 @@ export interface PineconeFieldMappingOptions { imageVectorFields?: string[]; } -/** A representation of the available Azure OpenAI enhancement configurations. */ -export interface AzureChatEnhancementConfiguration { - /** A representation of the available options for the Azure OpenAI grounding enhancement. */ - grounding?: AzureChatGroundingEnhancementConfiguration; - /** A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ - ocr?: AzureChatOCREnhancementConfiguration; -} - -/** A representation of the available options for the Azure OpenAI grounding enhancement. */ -export interface AzureChatGroundingEnhancementConfiguration { - /** Specifies whether the enhancement is enabled. */ - enabled: boolean; -} - -/** A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ -export interface AzureChatOCREnhancementConfiguration { - /** Specifies whether the enhancement is enabled. */ - enabled: boolean; -} - -/** A representation of a tool that can be used by the model to improve a chat completions response. */ -export type ChatCompletionsToolDefinition = ChatCompletionsFunctionToolDefinition; - -/** The definition information for a chat completions function tool that can call a function in response to a tool call. */ -export interface ChatCompletionsFunctionToolDefinition { - /** The object name, which is always 'function'. */ - type: "function"; - /** The function definition details for the function tool. */ - function: FunctionDefinition; -} - -/** A representation of an explicit, named tool selection to use for a chat completions request. */ -export type ChatCompletionsNamedToolSelection = - | ChatCompletionsToolSelectionPreset - | ChatCompletionsNamedFunctionToolSelection; - -/** A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ -export interface ChatCompletionsNamedFunctionToolSelection { - /** The object type, which is always 'function'. */ - type: "function"; - /** Specifies a tool the model should use. Used to force the model to call a specific function. */ - function: { - /** The name of the function that should be called. */ - name: string; - }; -} +/** The type of Azure Cognitive Search retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ +/** "simple", "semantic", "vector", "vectorSimpleHybrid", "vectorSemanticHybrid" */ +export type AzureCognitiveSearchQueryType = string; -/** A representation of a chat message as received in a response. */ -export interface ChatResponseMessage { - /** The chat role associated with the message. */ - role: ChatRole; - /** The content of the message. */ - content: string | null; - /** - * The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat - * completions request to resolve as configured. - */ - toolCalls: ChatCompletionsToolCall[]; - /** - * The function call that must be resolved and have its output appended to subsequent input messages for the chat - * completions request to resolve as configured. - */ - functionCall?: FunctionCall; - /** - * If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those - * extensions while processing the chat completions request. - */ - context?: AzureChatExtensionsMessageContext; +/** An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ +export interface OnYourDataVectorizationSource { + /** the discriminator possible values: Endpoint, DeploymentName, ModelId */ + type: OnYourDataVectorizationSourceType; } /** - * A representation of the additional context information available when Azure OpenAI chat extensions are involved - * in the generation of a corresponding chat completions response. This context information is only populated when - * using an Azure OpenAI request configured to use a matching extension. + * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + * on a public Azure OpenAI endpoint call for embeddings. */ -export interface AzureChatExtensionsMessageContext { - /** - * The contextual message payload associated with the Azure chat extensions used for a chat completions request. - * These messages describe the data source retrievals, plugin invocations, and other intermediate steps taken in the - * course of generating a chat completions response that was augmented by capabilities from Azure OpenAI chat - * extensions. - */ - messages?: ChatResponseMessage[]; +export interface OnYourDataEndpointVectorizationSource extends OnYourDataVectorizationSource { + /** The type of vectorization source to use. Always 'Endpoint' for this type. */ + type: "Endpoint"; + /** Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. */ + endpoint: string; + /** Specifies the authentication options to use when retrieving embeddings from the specified endpoint. */ + authentication: OnYourDataAuthenticationOptionsUnion; } -/** A structured representation of a stop reason that signifies natural termination by the model. */ -export interface StopFinishDetails { - /** The object type, which is always 'stop' for this object. */ - type: "stop"; - /** The token sequence that the model terminated with. */ - stop: string; +/** + * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + * on an internal embeddings model deployment name in the same Azure OpenAI resource. + */ +export interface OnYourDataDeploymentNameVectorizationSource extends OnYourDataVectorizationSource { + /** The type of vectorization source to use. Always 'DeploymentName' for this type. */ + type: "DeploymentName"; + /** The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. */ + deploymentName: string; } /** - * A structured representation of a stop reason that signifies a token limit was reached before the model could naturally - * complete. + * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based + * on a search service model ID. Currently only supported by Elasticsearch®. */ -export interface MaxTokensFinishDetails { - /** The object type, which is always 'max_tokens' for this object. */ - type: "max_tokens"; +export interface OnYourDataModelIdVectorizationSource extends OnYourDataVectorizationSource { + /** The type of vectorization source to use. Always 'ModelId' for this type. */ + type: "ModelId"; + /** The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. */ + modelId: string; } -/** Structured information about why a chat completions response terminated. */ -export type ChatFinishDetails = StopFinishDetails | MaxTokensFinishDetails; - /** - * Represents the output results of Azure enhancements to chat completions, as configured via the matching input provided - * in the request. + * Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with + * vector search. */ -export interface AzureChatEnhancements { - /** The grounding enhancement that returns the bounding box of the objects detected in the image. */ - grounding?: AzureGroundingEnhancement; -} - -/** The grounding enhancement that returns the bounding box of the objects detected in the image. */ -export interface AzureGroundingEnhancement { - /** The lines of text detected by the grounding enhancement. */ - lines: AzureGroundingEnhancementLine[]; -} - -/** A content line object consisting of an adjacent sequence of content elements, such as words and selection marks. */ -export interface AzureGroundingEnhancementLine { - /** The text within the line. */ - text: string; - /** An array of spans that represent detected objects and its bounding box information. */ - spans: AzureGroundingEnhancementLineSpan[]; -} - -/** A span object that represents a detected object and its bounding box information. */ -export interface AzureGroundingEnhancementLineSpan { - /** The text content of the span that represents the detected object. */ - text: string; - /** - * The character offset within the text where the span begins. This offset is defined as the position of the first - * character of the span, counting from the start of the text as Unicode codepoints. - */ - offset: number; - /** The length of the span in characters, measured in Unicode codepoints. */ - length: number; - /** An array of objects representing points in the polygon that encloses the detected object. */ - polygon: AzureGroundingEnhancementCoordinatePoint[]; -} - -/** A representation of a single polygon point as used by the Azure grounding enhancement. */ -export interface AzureGroundingEnhancementCoordinatePoint { - /** The x-coordinate (horizontal axis) of the point. */ - x: number; - /** The y-coordinate (vertical axis) of the point. */ - y: number; -} +/** "Endpoint", "DeploymentName", "ModelId" */ +export type OnYourDataVectorizationSourceType = string; -/** Represents the request data used to generate images. */ -export interface ImageGenerationOptions { - /** - * The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be - * inferred as a default. - */ - model?: string; - /** A description of the desired images. */ - prompt: string; - /** - * The number of images to generate. - * Dall-e-2 models support values between 1 and 10. - * Dall-e-3 models only support a value of 1. - */ - n?: number; - /** - * The desired dimensions for generated images. - * Dall-e-2 models support 256x256, 512x512, or 1024x1024. - * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. - */ - size?: ImageSize; - /** The format in which image generation response items should be presented. */ - responseFormat?: ImageGenerationResponseFormat; - /** - * The desired image generation quality level to use. - * Only configurable with dall-e-3 models. - */ - quality?: ImageGenerationQuality; +/** + * A specific representation of configurable options for Azure Machine Learning vector index when using it as an Azure + * OpenAI chat extension. + */ +export interface AzureMachineLearningIndexChatExtensionConfiguration { /** - * The desired image generation style to use. - * Only configurable with dall-e-3 models. + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Azure Machine Learning vector index. */ - style?: ImageGenerationStyle; - /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ - user?: string; -} - -/** The result of a successful image generation operation. */ -export interface ImageGenerations { + type: "AzureMLIndex"; /** - * A timestamp representing when this operation was started. - * Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + * The authentication method to use when accessing the defined data source. + * Each data source type supports a specific set of available authentication methods; please see the documentation of + * the data source for supported mechanisms. + * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + * authentication. */ - created: Date; - /** The images generated by the operation. */ - data: ImageGenerationData[]; + authentication?: OnYourDataAuthenticationOptionsUnion; + /** The configured top number of documents to feature for the configured query. */ + topNDocuments?: number; + /** Whether queries should be restricted to use of indexed data. */ + inScope?: boolean; + /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ + strictness?: number; + /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ + roleInformation?: string; + /** The resource ID of the Azure Machine Learning project. */ + projectResourceId: string; + /** The Azure Machine Learning vector index name. */ + name: string; + /** The version of the Azure Machine Learning vector index. */ + version: string; + /** Search filter. Only supported if the Azure Machine Learning vector index is of type AzureSearch. */ + filter?: string; } /** - * A representation of a single generated image, provided as either base64-encoded data or as a URL from which the image - * may be retrieved. + * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + * extension. */ -export interface ImageGenerationData { - /** The URL that provides temporary access to download the generated image. */ - url?: string; - /** The complete data for an image, represented as a base64-encoded string. */ - base64Data?: string; +export interface AzureCosmosDBChatExtensionConfiguration { /** - * The final prompt used by the model to generate the image. - * Only provided with dall-3-models and only when revisions were made to the prompt. + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Azure Cosmos DB. */ - revisedPrompt?: string; + type: "AzureCosmosDB"; + /** + * The authentication method to use when accessing the defined data source. + * Each data source type supports a specific set of available authentication methods; please see the documentation of + * the data source for supported mechanisms. + * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + * authentication. + */ + authentication?: OnYourDataAuthenticationOptionsUnion; + /** The configured top number of documents to feature for the configured query. */ + topNDocuments?: number; + /** Whether queries should be restricted to use of indexed data. */ + inScope?: boolean; + /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ + strictness?: number; + /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ + roleInformation?: string; + /** The MongoDB vCore database name to use with Azure Cosmos DB. */ + databaseName: string; + /** The name of the Azure Cosmos DB resource container. */ + containerName: string; + /** The MongoDB vCore index name to use with Azure Cosmos DB. */ + indexName: string; + /** Customized field mapping behavior to use when interacting with the search index. */ + fieldsMapping: AzureCosmosDBFieldMappingOptions; + /** The embedding dependency for vector search. */ + embeddingDependency?: OnYourDataVectorizationSourceUnion; +} +/** Optional settings to control how fields are processed when using a configured Azure Cosmos DB resource. */ +export interface AzureCosmosDBFieldMappingOptions { + /** The names of fields that represent vector data. */ + vectorFields: string[]; } /** - * The configuration information for an embeddings request. - * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, - * recommendations, and other similar scenarios. + * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + * extension. */ -export interface EmbeddingsOptions { - /** - * An identifier for the caller or end user of the operation. This may be used for tracking - * or rate-limiting purposes. - */ - user?: string; +export interface ElasticsearchChatExtensionConfiguration { /** - * The model name to provide as part of this embeddings request. - * Not applicable to Azure OpenAI, where deployment information should be included in the Azure - * resource URI that's connected to. + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Elasticsearch®. */ - model?: string; + type: "Elasticsearch"; /** - * Input texts to get embeddings for, encoded as a an array of strings. - * Each input must not exceed 2048 tokens in length. - * - * Unless you are embedding code, we suggest replacing newlines (\\n) in your input with a single space, - * as we have observed inferior results when newlines are present. + * The authentication method to use when accessing the defined data source. + * Each data source type supports a specific set of available authentication methods; please see the documentation of + * the data source for supported mechanisms. + * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + * authentication. */ - input: string[]; + authentication?: OnYourDataAuthenticationOptionsUnion; + /** The configured top number of documents to feature for the configured query. */ + topNDocuments?: number; + /** Whether queries should be restricted to use of indexed data. */ + inScope?: boolean; + /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ + strictness?: number; + /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ + roleInformation?: string; + /** The endpoint of Elasticsearch®. */ + endpoint: string; + /** The index name of Elasticsearch®. */ + indexName: string; + /** The index field mapping options of Elasticsearch®. */ + fieldsMapping?: ElasticsearchIndexFieldMappingOptions; + /** The query type of Elasticsearch®. */ + queryType?: ElasticsearchQueryType; + /** The embedding dependency for vector search. */ + embeddingDependency?: OnYourDataVectorizationSourceUnion; } -/** - * Representation of the response data from an embeddings request. - * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, - * recommendations, and other similar scenarios. - */ -export interface Embeddings { - /** Embedding values for the prompts submitted in the request. */ - data: EmbeddingItem[]; - /** Usage counts for tokens input using the embeddings API. */ - usage: EmbeddingsUsage; +/** Optional settings to control how fields are processed when using a configured Elasticsearch® resource. */ +export interface ElasticsearchIndexFieldMappingOptions { + /** The name of the index field to use as a title. */ + titleField?: string; + /** The name of the index field to use as a URL. */ + urlField?: string; + /** The name of the index field to use as a filepath. */ + filepathField?: string; + /** The names of index fields that should be treated as content. */ + contentFields?: string[]; + /** The separator pattern that content fields should use. */ + contentFieldsSeparator?: string; + /** The names of fields that represent vector data. */ + vectorFields?: string[]; } -/** Representation of a single embeddings relatedness comparison. */ -export interface EmbeddingItem { +/** The type of Elasticsearch® retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ +/** "simple", "vector" */ +export type ElasticsearchQueryType = string; + +/** + * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + * extension. + */ +export interface PineconeChatExtensionConfiguration { /** - * List of embeddings value for the input prompt. These represent a measurement of the - * vector-based relatedness of the provided input. + * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its + * default value for Pinecone. */ - embedding: number[]; - /** Index of the prompt to which the EmbeddingItem corresponds. */ - index: number; -} - -/** Measurement of the amount of tokens used in this request and response. */ -export interface EmbeddingsUsage { - /** Number of tokens sent in the original request. */ - promptTokens: number; - /** Total number of tokens transacted in this request/response. */ - totalTokens: number; + type: "Pinecone"; + /** + * The authentication method to use when accessing the defined data source. + * Each data source type supports a specific set of available authentication methods; please see the documentation of + * the data source for supported mechanisms. + * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) + * authentication. + */ + authentication?: OnYourDataAuthenticationOptions; + /** The configured top number of documents to feature for the configured query. */ + topNDocuments?: number; + /** Whether queries should be restricted to use of indexed data. */ + inScope?: boolean; + /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ + strictness?: number; + /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ + roleInformation?: string; + /** The environment name of Pinecone. */ + environment: string; + /** The name of the Pinecone database index. */ + indexName: string; + /** Customized field mapping behavior to use when interacting with the search index. */ + fieldsMapping: PineconeFieldMappingOptions; + /** The embedding dependency for vector search. */ + embeddingDependency?: OnYourDataVectorizationSource; } -/** Defines available options for the underlying response format of output transcription information. */ -/** "json", "verbose_json", "text", "srt", "vtt" */ -export type AudioTranscriptionFormat = string; -/** Defines the possible descriptors for available audio operation responses. */ -/** "transcribe", "translate" */ -export type AudioTaskLabel = string; -/** Defines available options for the underlying response format of output translation information. */ -/** "json", "verbose_json", "text", "srt", "vtt" */ -export type AudioTranslationFormat = string; -/** Ratings for the intensity and risk level of harmful content. */ -/** "safe", "low", "medium", "high" */ -export type ContentFilterSeverity = string; -/** Representation of the manner in which a completions response concluded. */ -/** "stop", "length", "content_filter", "function_call", "tool_calls" */ -export type CompletionsFinishReason = string; -/** A description of the intended purpose of a message within a chat completions interaction. */ -/** "system", "assistant", "user", "function", "tool" */ -export type ChatRole = string; /** - * The collection of predefined behaviors for handling request-provided function information in a chat completions - * operation. + * + * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat + * completions request that should use Azure OpenAI chat extensions to augment the response behavior. + * The use of this configuration is compatible only with Azure OpenAI. */ -/** "auto", "none" */ -export type FunctionCallPreset = "auto" | "none"; +export type AzureChatExtensionConfiguration = + | AzureCognitiveSearchChatExtensionConfiguration + | AzureMachineLearningIndexChatExtensionConfiguration + | AzureCosmosDBChatExtensionConfiguration + | ElasticsearchChatExtensionConfiguration + | PineconeChatExtensionConfiguration; + +/** Optional settings to control how fields are processed when using a configured Pinecone resource. */ +export interface PineconeFieldMappingOptions { + /** The name of the index field to use as a title. */ + titleField?: string; + /** The name of the index field to use as a URL. */ + urlField?: string; + /** The name of the index field to use as a filepath. */ + filepathField?: string; + /** The names of index fields that should be treated as content. */ + contentFields?: string[]; + /** The separator pattern that content fields should use. */ + contentFieldsSeparator?: string; + /** The names of fields that represent vector data. */ + vectorFields?: string[]; + /** The names of fields that represent image vector data. */ + imageVectorFields?: string[]; +} + /** * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat * completions request that should use Azure OpenAI chat extensions to augment the response behavior. @@ -897,159 +1184,82 @@ export type FunctionCallPreset = "auto" | "none"; */ /** "AzureCognitiveSearch", "AzureMLIndex", "AzureCosmosDB", "Elasticsearch", "Pinecone" */ export type AzureChatExtensionType = string; -/** The authentication types supported with Azure OpenAI On Your Data. */ -/** "APIKey", "ConnectionString", "KeyAndKeyId", "SystemAssignedManagedIdentity", "UserAssignedManagedIdentity" */ -export type OnYourDataAuthenticationType = - | "APIKey" - | "ConnectionString" - | "KeyAndKeyId" - | "SystemAssignedManagedIdentity" - | "UserAssignedManagedIdentity"; -/** The type of Azure Cognitive Search retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ -/** "simple", "semantic", "vector", "vectorSimpleHybrid", "vectorSemanticHybrid" */ -export type AzureCognitiveSearchQueryType = - | "simple" - | "semantic" - | "vector" - | "vectorSimpleHybrid" - | "vectorSemanticHybrid"; -/** - * Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with - * vector search. - */ -/** "Endpoint", "DeploymentName", "ModelId" */ -export type OnYourDataVectorizationSourceType = "Endpoint" | "DeploymentName" | "ModelId"; -/** The type of Elasticsearch® retrieval query that should be executed when using it as an Azure OpenAI chat extension. */ -/** "simple", "vector" */ -export type ElasticsearchQueryType = "simple" | "vector"; -/** The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response -content that adheres to a specific schema. */ -export interface ChatCompletionsTextResponseFormat { - /** The object type, which is always 'text' for this object. */ - type: "text"; +/** A representation of the available Azure OpenAI enhancement configurations. */ +export interface AzureChatEnhancementConfiguration { + /** A representation of the available options for the Azure OpenAI grounding enhancement. */ + grounding?: AzureChatGroundingEnhancementConfiguration; + /** A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ + ocr?: AzureChatOCREnhancementConfiguration; } -/** A response format for Chat Completions that restricts responses to emitting valid JSON objects. - */ -export interface ChatCompletionsJsonResponseFormat { - /** The object type, which is always 'json_object' for this object. */ - type: "json_object"; + +/** A representation of the available options for the Azure OpenAI grounding enhancement. */ +export interface AzureChatGroundingEnhancementConfiguration { + /** Specifies whether the enhancement is enabled. */ + enabled: boolean; } -/** The valid response formats Chat Completions can provide. Used to enable JSON mode. */ -export type ChatCompletionsResponseFormat = - | ChatCompletionsTextResponseFormat - | ChatCompletionsJsonResponseFormat; -/** Represents a generic policy for how a chat completions tool may be selected. */ -/** "auto", "none" */ -export type ChatCompletionsToolSelectionPreset = "auto" | "none"; -/** The desired size of generated images. */ -/** "1024x1024", "1792x1024", "1024x1792" */ -export type ImageSize = "1024x1024" | "1792x1024" | "1024x1792"; -/** The format in which the generated images are returned. */ -/** "url", "b64_json" */ -export type ImageGenerationResponseFormat = "url" | "b64_json"; -/** - * An image generation configuration that specifies how the model should prioritize quality, cost, and speed. - * Only configurable with dall-e-3 models. - */ -/** "standard", "hd" */ -export type ImageGenerationQuality = "standard" | "hd"; -/** - * An image generation configuration that specifies how the model should incorporate realism and other visual characteristics. - * Only configurable with dall-e-3 models. - */ -/** "natural", "vivid" */ -export type ImageGenerationStyle = "natural" | "vivid"; -/** - * The representation of a single prompt completion as part of an overall completions request. - * Generally, `n` choices are generated per provided prompt with a default value of 1. - * Token limits and other settings may limit the number of choices generated. - */ -export interface Choice { - /** The generated text for a given completions prompt. */ - text: string; - /** The ordered index associated with this completions choice. */ - index: number; - /** - * Information about the content filtering category (hate, sexual, violence, selfHarm), if it - * has been detected, as well as the severity level (very_low, low, medium, high-scale that - * determines the intensity and risk level of harmful content) and if it has been filtered or not. - */ - contentFilterResults?: ContentFilterResultsForChoice; - /** The log probabilities model for tokens associated with this completions choice. */ - logprobs: CompletionsLogProbabilityModel | null; - /** Reason for finishing */ - finishReason: CompletionsFinishReason | null; +/** A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. */ +export interface AzureChatOCREnhancementConfiguration { + /** Specifies whether the enhancement is enabled. */ + enabled: boolean; } /** - * Representation of the response data from a completions request. - * Completions support a wide variety of tasks and generate text that continues from or "completes" - * provided prompt data. + * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + * mode. */ -export interface Completions { - /** A unique identifier associated with this completions response. */ - id: string; - /** - * The first timestamp associated with generation activity for this completions response, - * represented as seconds since the beginning of the Unix epoch of 00:00 on 1 Jan 1970. - */ - created: Date; - /** - * Content filtering results for zero or more prompts in the request. In a streaming request, - * results for different prompts may arrive at different times or in different orders. - */ - promptFilterResults: ContentFilterResultsForPrompt[]; - /** - * The collection of completions choices associated with this completions response. - * Generally, `n` choices are generated per provided prompt with a default value of 1. - * Token limits and other settings may limit the number of choices generated. - */ - choices: Choice[]; - /** Usage information for tokens processed and generated as part of this completions operation. */ - usage: CompletionsUsage; +export interface ChatCompletionsResponseFormat { + /** the discriminator possible values: text, json_object */ + type: string; } /** - * The representation of a single prompt completion as part of an overall chat completions request. - * Generally, `n` choices are generated per provided prompt with a default value of 1. - * Token limits and other settings may limit the number of choices generated. + * The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response + * content that adheres to a specific schema. */ -export interface ChatChoice { - /** The chat message for a given chat completions prompt. */ - message?: ChatResponseMessage; - /** The ordered index associated with this chat completions choice. */ - index: number; - /** The reason that this chat completions choice completed its generated. */ - finishReason: CompletionsFinishReason | null; - /** - * The reason the model stopped generating tokens, together with any applicable details. - * This structured representation replaces 'finishReason' for some models. - */ - finishDetails?: ChatFinishDetails; - /** The delta message content for a streaming response. */ - delta?: ChatResponseMessage; - /** - * Information about the content filtering category (hate, sexual, violence, selfHarm), if it - * has been detected, as well as the severity level (very_low, low, medium, high-scale that - * determines the intensity and risk level of harmful content) and if it has been filtered or not. - */ - contentFilterResults?: ContentFilterResultsForChoice; - /** - * Represents the output results of Azure OpenAI enhancements to chat completions, as configured via the matching input - * provided in the request. This supplementary information is only available when using Azure OpenAI and only when the - * request is configured to use enhancements. - */ - enhancements?: AzureChatEnhancements; +export interface ChatCompletionsTextResponseFormat extends ChatCompletionsResponseFormat { + /** The discriminated object type, which is always 'text' for this format. */ + type: "text"; } -/** Content filtering results for a single prompt in the request. */ -export interface ContentFilterResultsForPrompt { - /** The index of this prompt in the set of prompt results */ - promptIndex: number; - /** Content filtering results for this prompt */ - contentFilterResults: ContentFilterResultDetailsForPrompt; +/** A response format for Chat Completions that restricts responses to emitting valid JSON objects. */ +export interface ChatCompletionsJsonResponseFormat extends ChatCompletionsResponseFormat { + /** The discriminated object type, which is always 'json_object' for this format. */ + type: "json_object"; +} + +/** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ +export interface ChatCompletionsToolDefinition { + /** the discriminator possible values: function */ + type: string; +} + +/** The definition information for a chat completions function tool that can call a function in response to a tool call. */ +export interface ChatCompletionsFunctionToolDefinition extends ChatCompletionsToolDefinition { + /** The object name, which is always 'function'. */ + type: "function"; + /** The function definition details for the function tool. */ + function: FunctionDefinition; +} + +/** Represents a generic policy for how a chat completions tool may be selected. */ +/** "auto", "none" */ +export type ChatCompletionsToolSelectionPreset = string; + +/** An abstract representation of an explicit, named tool selection to use for a chat completions request. */ +export interface ChatCompletionsNamedToolSelection { + /** the discriminator possible values: function */ + type: string; +} + +/** A tool selection of a specific, named function tool that will limit chat completions to using the named function. */ +export interface ChatCompletionsNamedFunctionToolSelection + extends ChatCompletionsNamedToolSelection { + /** The object type, which is always 'function'. */ + type: "function"; + /** The name of the function that should be called. */ + name: string; } /** @@ -1072,500 +1282,346 @@ export interface ChatCompletions { */ choices: ChatChoice[]; /** - * Content filtering results for zero or more prompts in the request. In a streaming request, - * results for different prompts may arrive at different times or in different orders. - */ - promptFilterResults: ContentFilterResultsForPrompt[]; - /** - * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that - * might impact determinism. - */ - systemFingerprint?: string; - /** Usage information for tokens processed and generated as part of this completions operation. */ - usage?: CompletionsUsage; -} - -/** Information about the content filtering category, if it has been detected. */ -export type ContentFilterResultDetailsForPrompt = - | ContentFilterSuccessResultDetailsForPrompt - | ContentFilterErrorResults; - -/** Information about the content filtering success result. */ -export interface ContentFilterSuccessResultDetailsForPrompt { - /** - * Describes language related to anatomical organs and genitals, romantic relationships, - * acts portrayed in erotic or affectionate terms, physical sexual acts, including - * those portrayed as an assault or a forced sexual violent act against one’s will, - * prostitution, pornography, and abuse. - */ - sexual?: ContentFilterResult; - /** - * Describes language related to physical actions intended to hurt, injure, damage, or - * kill someone or something; describes weapons, etc. - */ - violence?: ContentFilterResult; - /** - * Describes language attacks or uses that include pejorative or discriminatory language - * with reference to a person or identity group on the basis of certain differentiating - * attributes of these groups including but not limited to race, ethnicity, nationality, - * gender identity and expression, sexual orientation, religion, immigration status, ability - * status, personal appearance, and body size. - */ - hate?: ContentFilterResult; - /** - * Describes language related to physical actions intended to purposely hurt, injure, - * or damage one’s body, or kill oneself. - */ - selfHarm?: ContentFilterResult; - /** - * Describes an error returned if the content filtering system is - * down or otherwise unable to complete the operation in time. - */ - error?: undefined; - /** Describes whether profanity was detected. */ - profanity?: ContentFilterDetectionResult; - /** Describes detection results against configured custom blocklists. */ - customBlocklists?: ContentFilterBlocklistIdResult[]; - /** Whether a jailbreak attempt was detected in the prompt. */ - jailbreak?: ContentFilterDetectionResult; -} - -/** Information about the content filtering error result. */ -export interface ContentFilterErrorResults { - /** - * Describes an error returned if the content filtering system is - * down or otherwise unable to complete the operation in time. - */ - error: ErrorModel; -} - -/** Information about content filtering evaluated against generated model output. */ -export interface ContentFilterSuccessResultsForChoice { - /** - * Describes language related to anatomical organs and genitals, romantic relationships, - * acts portrayed in erotic or affectionate terms, physical sexual acts, including - * those portrayed as an assault or a forced sexual violent act against one’s will, - * prostitution, pornography, and abuse. - */ - sexual?: ContentFilterResult; - /** - * Describes language related to physical actions intended to hurt, injure, damage, or - * kill someone or something; describes weapons, etc. - */ - violence?: ContentFilterResult; - /** - * Describes language attacks or uses that include pejorative or discriminatory language - * with reference to a person or identity group on the basis of certain differentiating - * attributes of these groups including but not limited to race, ethnicity, nationality, - * gender identity and expression, sexual orientation, religion, immigration status, ability - * status, personal appearance, and body size. - */ - hate?: ContentFilterResult; - /** - * Describes language related to physical actions intended to purposely hurt, injure, - * or damage one’s body, or kill oneself. - */ - selfHarm?: ContentFilterResult; - /** Describes whether profanity was detected. */ - profanity?: ContentFilterDetectionResult; - /** Describes detection results against configured custom blocklists. */ - customBlocklists?: ContentFilterBlocklistIdResult[]; - /** - * Describes an error returned if the content filtering system is - * down or otherwise unable to complete the operation in time. + * Content filtering results for zero or more prompts in the request. In a streaming request, + * results for different prompts may arrive at different times or in different orders. */ - error?: undefined; - /** Information about detection of protected text material. */ - protectedMaterialText?: ContentFilterDetectionResult; - /** Information about detection of protected code material. */ - protectedMaterialCode?: ContentFilterCitedDetectionResult; + promptFilterResults: ContentFilterResultsForPrompt[]; + /** + * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that + * might impact determinism. + */ + systemFingerprint?: string; + /** Usage information for tokens processed and generated as part of this completions operation. */ + usage?: CompletionsUsage; } -/** Information about the content filtering results, if it has been detected. */ -export type ContentFilterResultsForChoice = - | ContentFilterSuccessResultsForChoice - | ContentFilterErrorResults; - /** - * A request chat message containing system instructions that influence how the model will generate a chat completions - * response. + * The representation of a single prompt completion as part of an overall chat completions request. + * Generally, `n` choices are generated per provided prompt with a default value of 1. + * Token limits and other settings may limit the number of choices generated. */ -export interface ChatRequestSystemMessage { - /** The chat role associated with this message, which is always 'system' for system messages. */ - role: "system"; - /** The contents of the system message. */ - content: string; - /** An optional name for the participant. */ - name?: string; +export interface ChatChoice { + /** The chat message for a given chat completions prompt. */ + message?: ChatResponseMessage; + /** The ordered index associated with this chat completions choice. */ + index: number; + /** The reason that this chat completions choice completed its generated. */ + finishReason: CompletionsFinishReason | null; + /** + * The reason the model stopped generating tokens, together with any applicable details. + * This structured representation replaces 'finish_reason' for some models. + */ + finishDetails?: ChatFinishDetailsUnion; + /** The delta message content for a streaming response. */ + delta?: ChatResponseMessage; + /** + * Information about the content filtering category (hate, sexual, violence, self_harm), if it + * has been detected, as well as the severity level (very_low, low, medium, high-scale that + * determines the intensity and risk level of harmful content) and if it has been filtered or not. + */ + contentFilterResults?: ContentFilterResultsForChoice; + /** + * Represents the output results of Azure OpenAI enhancements to chat completions, as configured via the matching input + * provided in the request. This supplementary information is only available when using Azure OpenAI and only when the + * request is configured to use enhancements. + */ + enhancements?: AzureChatEnhancements; } -/** A request chat message representing response or action from the assistant. */ -export interface ChatRequestAssistantMessage { - /** The chat role associated with this message, which is always 'assistant' for assistant messages. */ - role: "assistant"; +/** A representation of a chat message as received in a response. */ +export interface ChatResponseMessage { + /** The chat role associated with the message. */ + role: ChatRole; /** The content of the message. */ content: string | null; - /** An optional name for the participant. */ - name?: string; /** * The tool calls that must be resolved and have their outputs appended to subsequent input messages for the chat * completions request to resolve as configured. */ - toolCalls?: Array; + toolCalls: ChatCompletionsToolCallUnion[]; /** * The function call that must be resolved and have its output appended to subsequent input messages for the chat * completions request to resolve as configured. */ functionCall?: FunctionCall; + /** + * If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those + * extensions while processing the chat completions request. + */ + context?: AzureChatExtensionsMessageContext; } -/** A request chat message representing user input to the assistant. */ -export interface ChatRequestUserMessage { - /** The chat role associated with this message, which is always 'user' for user messages. */ - role: "user"; - /** The contents of the user message, with available input types varying by selected model. */ - content: string | Array; - /** An optional name for the participant. */ - name?: string; +/** + * A representation of the additional context information available when Azure OpenAI chat extensions are involved + * in the generation of a corresponding chat completions response. This context information is only populated when + * using an Azure OpenAI request configured to use a matching extension. + */ +export interface AzureChatExtensionsMessageContext { + /** + * The contextual message payload associated with the Azure chat extensions used for a chat completions request. + * These messages describe the data source retrievals, plugin invocations, and other intermediate steps taken in the + * course of generating a chat completions response that was augmented by capabilities from Azure OpenAI chat + * extensions. + */ + messages?: ChatResponseMessage[]; } -/** A request chat message representing requested output from a configured tool. */ -export interface ChatRequestToolMessage { - /** The chat role associated with this message, which is always 'tool' for tool messages. */ - role: "tool"; - /** The content of the message. */ - content: string | null; - /** The ID of the tool call resolved by the provided content. */ - toolCallId: string; +/** An abstract representation of structured information about why a chat completions response terminated. */ +export interface ChatFinishDetails { + /** the discriminator possible values: stop, max_tokens */ + type: string; } -/** A request chat message representing requested output from a configured function. */ -export interface ChatRequestFunctionMessage { - /** The chat role associated with this message, which is always 'function' for function messages. */ - role: "function"; - /** The name of the function that was called to produce output. */ - name: string; - /** The output of the function as requested by the function call. */ - content: string | null; +/** A structured representation of a stop reason that signifies natural termination by the model. */ +export interface StopFinishDetails extends ChatFinishDetails { + /** The object type, which is always 'stop' for this object. */ + type: "stop"; + /** The token sequence that the model terminated with. */ + stop: string; } -/** An abstract representation of a chat message as provided in a request. */ -export type ChatRequestMessage = - | ChatRequestSystemMessage - | ChatRequestUserMessage - | ChatRequestAssistantMessage - | ChatRequestToolMessage - | ChatRequestFunctionMessage; - /** - * Options for Azure OpenAI chat extensions. + * A structured representation of a stop reason that signifies a token limit was reached before the model could naturally + * complete. */ -export interface AzureExtensionsOptions { - /** - * The configuration entries for Azure OpenAI chat extensions that use them. - * This additional specification is only compatible with Azure OpenAI. - */ - extensions?: AzureChatExtensionConfiguration[]; - /** If provided, the configuration options for available Azure OpenAI chat enhancements. */ - enhancements?: AzureChatEnhancementConfiguration; +export interface MaxTokensFinishDetails extends ChatFinishDetails { + /** The object type, which is always 'max_tokens' for this object. */ + type: "max_tokens"; } /** - * A specific representation of configurable options for Azure Cognitive Search when using it as an Azure OpenAI chat - * extension. + * Represents the output results of Azure enhancements to chat completions, as configured via the matching input provided + * in the request. */ -export interface AzureCognitiveSearchChatExtensionConfiguration { - /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Azure Cognitive Search. - */ - type: "AzureCognitiveSearch"; +export interface AzureChatEnhancements { + /** The grounding enhancement that returns the bounding box of the objects detected in the image. */ + grounding?: AzureGroundingEnhancement; +} + +/** The grounding enhancement that returns the bounding box of the objects detected in the image. */ +export interface AzureGroundingEnhancement { + /** The lines of text detected by the grounding enhancement. */ + lines: AzureGroundingEnhancementLine[]; +} + +/** A content line object consisting of an adjacent sequence of content elements, such as words and selection marks. */ +export interface AzureGroundingEnhancementLine { + /** The text within the line. */ + text: string; + /** An array of spans that represent detected objects and its bounding box information. */ + spans: AzureGroundingEnhancementLineSpan[]; +} + +/** A span object that represents a detected object and its bounding box information. */ +export interface AzureGroundingEnhancementLineSpan { + /** The text content of the span that represents the detected object. */ + text: string; /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. + * The character offset within the text where the span begins. This offset is defined as the position of the first + * character of the span, counting from the start of the text as Unicode codepoints. */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The absolute endpoint path for the Azure Cognitive Search resource to use. */ - endpoint: string; - /** The name of the index to use as available in the referenced Azure Cognitive Search resource. */ - indexName: string; - /** The API key to use when interacting with the Azure Cognitive Search resource. */ - key?: string; - /** Customized field mapping behavior to use when interacting with the search index. */ - fieldsMapping?: AzureCognitiveSearchIndexFieldMappingOptions; - /** The query type to use with Azure Cognitive Search. */ - queryType?: AzureCognitiveSearchQueryType; - /** The additional semantic configuration for the query. */ - semanticConfiguration?: string; - /** Search filter. */ - filter?: string; - /** When using embeddings for search, specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of format `https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings?api-version={api-version}`. */ - embeddingEndpoint?: string; - /** When using embeddings, specifies the API key to use with the provided embeddings endpoint. */ - embeddingKey?: string; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + offset: number; + /** The length of the span in characters, measured in Unicode codepoints. */ + length: number; + /** An array of objects representing points in the polygon that encloses the detected object. */ + polygon: AzureGroundingEnhancementCoordinatePoint[]; } -/** - * A specific representation of configurable options for Azure Machine Learning vector index when using it as an Azure - * OpenAI chat extension. - */ -export interface AzureMachineLearningIndexChatExtensionConfiguration { +/** A representation of a single polygon point as used by the Azure grounding enhancement. */ +export interface AzureGroundingEnhancementCoordinatePoint { + /** The x-coordinate (horizontal axis) of the point. */ + x: number; + /** The y-coordinate (vertical axis) of the point. */ + y: number; +} + +/** Represents the request data used to generate images. */ +export interface ImageGenerationOptions { /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Azure Machine Learning vector index. + * The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be + * inferred as a default. */ - type: "AzureMLIndex"; + model?: string; + /** A description of the desired images. */ + prompt: string; /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. + * The number of images to generate. + * Dall-e-2 models support values between 1 and 10. + * Dall-e-3 models only support a value of 1. */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The resource ID of the Azure Machine Learning project. */ - projectResourceId: string; - /** The Azure Machine Learning vector index name. */ - name: string; - /** The version of the Azure Machine Learning vector index. */ - version: string; - /** Search filter. Only supported if the Azure Machine Learning vector index is of type AzureSearch. */ - filter?: string; -} - -/** - * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat - * extension. - */ -export interface AzureCosmosDBChatExtensionConfiguration { + n?: number; /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Azure Cosmos DB. + * The desired dimensions for generated images. + * Dall-e-2 models support 256x256, 512x512, or 1024x1024. + * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. */ - type: "AzureCosmosDB"; + size?: ImageSize; + /** The format in which image generation response items should be presented. */ + responseFormat?: ImageGenerationResponseFormat; /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. + * The desired image generation quality level to use. + * Only configurable with dall-e-3 models. */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The MongoDB vCore database name to use with Azure Cosmos DB. */ - databaseName: string; - /** The name of the Azure Cosmos DB resource container. */ - containerName: string; - /** The MongoDB vCore index name to use with Azure Cosmos DB. */ - indexName: string; - /** Customized field mapping behavior to use when interacting with the search index. */ - fieldsMapping: AzureCosmosDBFieldMappingOptions; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + quality?: ImageGenerationQuality; + /** + * The desired image generation style to use. + * Only configurable with dall-e-3 models. + */ + style?: ImageGenerationStyle; + /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ + user?: string; } +/** The desired size of generated images. */ +/** "256x256", "512x512", "1024x1024", "1792x1024", "1024x1792" */ +export type ImageSize = string; +/** The format in which the generated images are returned. */ +/** "url", "b64_json" */ +export type ImageGenerationResponseFormat = string; /** - * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat - * extension. + * An image generation configuration that specifies how the model should prioritize quality, cost, and speed. + * Only configurable with dall-e-3 models. */ -export interface ElasticsearchChatExtensionConfiguration { +/** "standard", "hd" */ +export type ImageGenerationQuality = string; +/** + * An image generation configuration that specifies how the model should incorporate realism and other visual characteristics. + * Only configurable with dall-e-3 models. + */ +/** "natural", "vivid" */ +export type ImageGenerationStyle = string; + +/** The result of a successful image generation operation. */ +export interface ImageGenerations { /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Elasticsearch®. + * A timestamp representing when this operation was started. + * Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. */ - type: "Elasticsearch"; + created: Date; + /** The images generated by the operation. */ + data: ImageGenerationData[]; +} + +/** + * A representation of a single generated image, provided as either base64-encoded data or as a URL from which the image + * may be retrieved. + */ +export interface ImageGenerationData { + /** The URL that provides temporary access to download the generated image. */ + url?: string; + /** The complete data for an image, represented as a base64-encoded string. */ + base64Data?: string; /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. + * The final prompt used by the model to generate the image. + * Only provided with dall-3-models and only when revisions were made to the prompt. */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The endpoint of Elasticsearch®. */ - endpoint: string; - /** The index name of Elasticsearch®. */ - indexName: string; - /** The index field mapping options of Elasticsearch®. */ - fieldsMapping?: ElasticsearchIndexFieldMappingOptions; - /** The query type of Elasticsearch®. */ - queryType?: ElasticsearchQueryType; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + revisedPrompt?: string; } /** - * A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat - * extension. + * The configuration information for an embeddings request. + * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + * recommendations, and other similar scenarios. */ -export interface PineconeChatExtensionConfiguration { +export interface EmbeddingsOptions { /** - * The type label to use when configuring Azure OpenAI chat extensions. This should typically not be changed from its - * default value for Pinecone. + * An identifier for the caller or end user of the operation. This may be used for tracking + * or rate-limiting purposes. */ - type: "Pinecone"; + user?: string; /** - * The authentication method to use when accessing the defined data source. - * Each data source type supports a specific set of available authentication methods; please see the documentation of - * the data source for supported mechanisms. - * If not otherwise provided, On Your Data will attempt to use System Managed Identity (default credential) - * authentication. + * The model name to provide as part of this embeddings request. + * Not applicable to Azure OpenAI, where deployment information should be included in the Azure + * resource URI that's connected to. */ - authentication?: OnYourDataAuthenticationOptions; - /** The configured top number of documents to feature for the configured query. */ - topNDocuments?: number; - /** Whether queries should be restricted to use of indexed data. */ - inScope?: boolean; - /** The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. */ - strictness?: number; - /** Give the model instructions about how it should behave and any context it should reference when generating a response. You can describe the assistant's personality and tell it how to format responses. There's a 100 token limit for it, and it counts against the overall token limit. */ - roleInformation?: string; - /** The environment name of Pinecone. */ - environment: string; - /** The name of the Pinecone database index. */ - indexName: string; - /** Customized field mapping behavior to use when interacting with the search index. */ - fieldsMapping: PineconeFieldMappingOptions; - /** The embedding dependency for vector search. */ - embeddingDependency?: OnYourDataVectorizationSource; + model?: string; + /** + * Input texts to get embeddings for, encoded as a an array of strings. + * Each input must not exceed 2048 tokens in length. + * + * Unless you are embedding code, we suggest replacing newlines (\\n) in your input with a single space, + * as we have observed inferior results when newlines are present. + */ + input: string[]; } /** - * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat - * completions request that should use Azure OpenAI chat extensions to augment the response behavior. - * The use of this configuration is compatible only with Azure OpenAI. + * Representation of the response data from an embeddings request. + * Embeddings measure the relatedness of text strings and are commonly used for search, clustering, + * recommendations, and other similar scenarios. */ -export type AzureChatExtensionConfiguration = - | AzureCognitiveSearchChatExtensionConfiguration - | AzureMachineLearningIndexChatExtensionConfiguration - | AzureCosmosDBChatExtensionConfiguration - | ElasticsearchChatExtensionConfiguration - | PineconeChatExtensionConfiguration; - -/** The authentication options for Azure OpenAI On Your Data when using an API key. */ -export interface OnYourDataApiKeyAuthenticationOptions { - /** The authentication type of API key. */ - type: "APIKey"; - /** The API key to use for authentication. */ - key: string; -} - -/** The authentication options for Azure OpenAI On Your Data when using a connection string. */ -export interface OnYourDataConnectionStringAuthenticationOptions { - /** The authentication type of connection string. */ - type: "ConnectionString"; - /** The connection string to use for authentication. */ - connectionString: string; -} - -/** The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. */ -export interface OnYourDataKeyAndKeyIdAuthenticationOptions { - /** The authentication type of Elasticsearch key and key ID pair. */ - type: "KeyAndKeyId"; - /** The key to use for authentication. */ - key: string; - /** The key ID to use for authentication. */ - keyId: string; +export interface Embeddings { + /** Embedding values for the prompts submitted in the request. */ + data: EmbeddingItem[]; + /** Usage counts for tokens input using the embeddings API. */ + usage: EmbeddingsUsage; } -/** The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. */ -export interface OnYourDataSystemAssignedManagedIdentityAuthenticationOptions { - /** The authentication type of system-assigned managed identity. */ - type: "SystemAssignedManagedIdentity"; +/** Representation of a single embeddings relatedness comparison. */ +export interface EmbeddingItem { + /** + * List of embeddings value for the input prompt. These represent a measurement of the + * vector-based relatedness of the provided input. + */ + embedding: number[]; + /** Index of the prompt to which the EmbeddingItem corresponds. */ + index: number; } -/** The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. */ -export interface OnYourDataUserAssignedManagedIdentityAuthenticationOptions { - /** The authentication type of user-assigned managed identity. */ - type: "UserAssignedManagedIdentity"; - /** The resource ID of the user-assigned managed identity to use for authentication. */ - managedIdentityResourceId: string; +/** Measurement of the amount of tokens used in this request and response. */ +export interface EmbeddingsUsage { + /** Number of tokens sent in the original request. */ + promptTokens: number; + /** Total number of tokens transacted in this request/response. */ + totalTokens: number; } -/** The authentication options for Azure OpenAI On Your Data. */ -export type OnYourDataAuthenticationOptions = +/** Alias for ChatRequestMessageUnion */ +export type ChatRequestMessageUnion = + | ChatRequestSystemMessage + | ChatRequestUserMessage + | ChatRequestAssistantMessage + | ChatRequestToolMessage + | ChatRequestFunctionMessage + | ChatRequestMessage; +/** Alias for ChatMessageContentItemUnion */ +export type ChatMessageContentItemUnion = + | ChatMessageTextContentItem + | ChatMessageImageContentItem + | ChatMessageContentItem; +/** Alias for ChatCompletionsToolCallUnion */ +export type ChatCompletionsToolCallUnion = + | ChatCompletionsFunctionToolCall + | ChatCompletionsToolCall; +/** Alias for OnYourDataAuthenticationOptionsUnion */ +export type OnYourDataAuthenticationOptionsUnion = | OnYourDataApiKeyAuthenticationOptions | OnYourDataConnectionStringAuthenticationOptions | OnYourDataKeyAndKeyIdAuthenticationOptions | OnYourDataSystemAssignedManagedIdentityAuthenticationOptions - | OnYourDataUserAssignedManagedIdentityAuthenticationOptions; - -/** - * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based - * on a public Azure OpenAI endpoint call for embeddings. - */ -export interface OnYourDataEndpointVectorizationSource { - /** The type of vectorization source to use. Always 'Endpoint' for this type. */ - type: "Endpoint"; - /** Specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings. The api-version query parameter is not allowed. */ - endpoint: string; - /** Specifies the authentication options to use when retrieving embeddings from the specified endpoint. */ - authentication: OnYourDataAuthenticationOptions; -} - -/** - * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based - * on an internal embeddings model deployment name in the same Azure OpenAI resource. - */ -export interface OnYourDataDeploymentNameVectorizationSource { - /** The type of vectorization source to use. Always 'DeploymentName' for this type. */ - type: "DeploymentName"; - /** The embedding model deployment name within the same Azure OpenAI resource. This enables you to use vector search without Azure OpenAI api-key and without Azure OpenAI public network access. */ - deploymentName: string; -} - -/** - * The details of a a vectorization source, used by Azure OpenAI On Your Data when applying vector search, that is based - * on a search service model ID. Currently only supported by Elasticsearch®. - */ -export interface OnYourDataModelIdVectorizationSource { - /** The type of vectorization source to use. Always 'ModelId' for this type. */ - type: "ModelId"; - /** The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. */ - modelId: string; -} - -/** A representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ -export type OnYourDataVectorizationSource = + | OnYourDataUserAssignedManagedIdentityAuthenticationOptions + | OnYourDataAuthenticationOptions; +/** Alias for OnYourDataVectorizationSourceUnion */ +export type OnYourDataVectorizationSourceUnion = | OnYourDataEndpointVectorizationSource | OnYourDataDeploymentNameVectorizationSource - | OnYourDataModelIdVectorizationSource; - + | OnYourDataModelIdVectorizationSource + | OnYourDataVectorizationSource; +/** Alias for ChatCompletionsResponseFormatUnion */ +export type ChatCompletionsResponseFormatUnion = + | ChatCompletionsTextResponseFormat + | ChatCompletionsJsonResponseFormat + | ChatCompletionsResponseFormat; +/** Alias for ChatCompletionsToolDefinitionUnion */ +export type ChatCompletionsToolDefinitionUnion = + | ChatCompletionsFunctionToolDefinition + | ChatCompletionsToolDefinition; +/** Alias for ChatCompletionsNamedToolSelectionUnion */ +export type ChatCompletionsNamedToolSelectionUnion = + | ChatCompletionsNamedFunctionToolSelection + | ChatCompletionsToolSelectionPreset + | ChatCompletionsNamedToolSelection; +/** Alias for ChatFinishDetailsUnion */ +export type ChatFinishDetailsUnion = StopFinishDetails | MaxTokensFinishDetails | ChatFinishDetails; /** A readable stream that is iterable and disposable. */ export interface EventStream extends ReadableStream, AsyncIterable {} diff --git a/sdk/openai/openai/src/models/options.ts b/sdk/openai/openai/src/models/options.ts index 8f46f7ea4d25..3973c014c961 100644 --- a/sdk/openai/openai/src/models/options.ts +++ b/sdk/openai/openai/src/models/options.ts @@ -1,20 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { OperationOptions } from "@azure-rest/core-client"; import { AzureExtensionsOptions, - ChatCompletionsNamedToolSelection, + ChatCompletionsNamedToolSelectionUnion, ChatCompletionsResponseFormat, - ChatCompletionsToolDefinition, + ChatCompletionsToolDefinitionUnion, FunctionCallPreset, FunctionDefinition, FunctionName, @@ -24,33 +16,25 @@ import { ImageSize, } from "./models.js"; -export interface ClientOpenAIClientGetAudioTranscriptionAsPlainTextOptions - extends OperationOptions {} +export interface GetAudioTranscriptionAsPlainTextOptions extends OperationOptions {} -export interface ClientOpenAIClientGetAudioTranscriptionAsResponseObjectOptions - extends OperationOptions { +export interface GetAudioTranscriptionAsResponseObjectOptions extends OperationOptions { /** The content type for the operation. Always multipart/form-data for this operation. */ contentType?: string; } -export interface ClientOpenAIClientGetAudioTranslationAsPlainTextOptions extends OperationOptions {} +export interface GetAudioTranslationAsPlainTextOptions extends OperationOptions {} -export interface ClientOpenAIClientGetAudioTranslationAsResponseObjectOptions - extends OperationOptions { +export interface GetAudioTranslationAsResponseObjectOptions extends OperationOptions { /** The content type for the operation. Always multipart/form-data for this operation. */ contentType?: string; } -export interface ClientOpenAIClientGetCompletionsOptions extends OperationOptions {} - -export interface ClientOpenAIClientGetChatCompletionsOptions extends OperationOptions {} - -export interface ClientOpenAIClientGetChatCompletionsWithAzureExtensionsOptions - extends OperationOptions {} +export interface GeneratedGetChatCompletionsOptions extends OperationOptions {} -export interface ClientOpenAIClientGetImageGenerationsOptions extends OperationOptions {} +export interface GetChatCompletionsWithAzureExtensionsOptions extends OperationOptions {} -export interface ClientOpenAIClientGetEmbeddingsOptions extends OperationOptions {} +export interface GetImageGenerationsOptions extends OperationOptions {} /** Represents the request data used to generate images. */ export interface GetImagesOptions extends OperationOptions { @@ -255,9 +239,9 @@ export interface GetChatCompletionsOptions extends OperationOptions { /** An object specifying the format that the model must output. Used to enable JSON mode. */ responseFormat?: ChatCompletionsResponseFormat; /** The available tool definitions that the chat completions request can use, including caller-defined functions. */ - tools?: ChatCompletionsToolDefinition[]; + tools?: ChatCompletionsToolDefinitionUnion[]; /** If specified, the model will configure which of the provided tools it can use for the chat completions response. */ - toolChoice?: ChatCompletionsNamedToolSelection; + toolChoice?: ChatCompletionsNamedToolSelectionUnion; /** * The configuration entries for Azure OpenAI chat extensions that use them. * This additional specification is only compatible with Azure OpenAI. diff --git a/sdk/openai/openai/src/rest/clientDefinitions.ts b/sdk/openai/openai/src/rest/clientDefinitions.ts index ce677fe07ea2..e9974f529a09 100644 --- a/sdk/openai/openai/src/rest/clientDefinitions.ts +++ b/sdk/openai/openai/src/rest/clientDefinitions.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { GetAudioTranscriptionAsPlainTextParameters, GetAudioTranscriptionAsResponseObjectParameters, diff --git a/sdk/openai/openai/src/rest/index.ts b/sdk/openai/openai/src/rest/index.ts index 055ca3265b92..a2d1968f9077 100644 --- a/sdk/openai/openai/src/rest/index.ts +++ b/sdk/openai/openai/src/rest/index.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import OpenAIClient from "./openAIClient.js"; export * from "./openAIClient.js"; diff --git a/sdk/openai/openai/src/rest/isUnexpected.ts b/sdk/openai/openai/src/rest/isUnexpected.ts index b2ccd9ed7a4e..f9ad3ca93c31 100644 --- a/sdk/openai/openai/src/rest/isUnexpected.ts +++ b/sdk/openai/openai/src/rest/isUnexpected.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { GetAudioTranscriptionAsPlainText200Response, GetAudioTranscriptionAsResponseObject200Response, diff --git a/sdk/openai/openai/src/rest/models.ts b/sdk/openai/openai/src/rest/models.ts index 4b4884dcaf41..f153fcca70dc 100644 --- a/sdk/openai/openai/src/rest/models.ts +++ b/sdk/openai/openai/src/rest/models.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - /** The configuration information for an audio transcription request. */ export interface AudioTranscriptionOptions { /** @@ -21,7 +13,7 @@ export interface AudioTranscriptionOptions { /** * The requested format of the transcription response data, which will influence the content and detail of the result. * - * Possible values: json, verbose_json, text, srt, vtt + * Possible values: "json", "verbose_json", "text", "srt", "vtt" */ response_format?: string; /** @@ -57,7 +49,7 @@ export interface AudioTranslationOptions { /** * The requested format of the translation response data, which will influence the content and detail of the result. * - * Possible values: json, verbose_json, text, srt, vtt + * Possible values: "json", "verbose_json", "text", "srt", "vtt" */ response_format?: string; /** @@ -265,11 +257,7 @@ export interface ChatCompletionsOptions { * system_fingerprint response parameter to monitor changes in the backend." */ seed?: number; - /** - * An object specifying the format that the model must output. Used to enable JSON mode. - * - * Possible values: text, json_object - */ + /** An object specifying the format that the model must output. Used to enable JSON mode. */ response_format?: ChatCompletionsResponseFormat; /** The available tool definitions that the chat completions request can use, including caller-defined functions. */ tools?: Array; @@ -334,7 +322,7 @@ export interface ChatMessageImageUrl { * The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and * accuracy. * - * Possible values: auto, low, high + * Possible values: "auto", "low", "high" */ detail?: string; } @@ -488,14 +476,14 @@ export interface AzureCognitiveSearchChatExtensionParameters { /** * The query type to use with Azure Cognitive Search. * - * Possible values: simple, semantic, vector, vectorSimpleHybrid, vectorSemanticHybrid + * Possible values: "simple", "semantic", "vector", "vectorSimpleHybrid", "vectorSemanticHybrid" */ queryType?: string; /** The additional semantic configuration for the query. */ semanticConfiguration?: string; /** Search filter. */ filter?: string; - /** When using embeddings for search, specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of format `https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings?api-version={api-version}`. */ + /** When using embeddings for search, specifies the resource endpoint URL from which embeddings should be retrieved. It should be in the format of format https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/embeddings?api-version=\{api-version\}. */ embeddingEndpoint?: string; /** When using embeddings, specifies the API key to use with the provided embeddings endpoint. */ embeddingKey?: string; @@ -751,7 +739,7 @@ export interface ElasticsearchChatExtensionParameters { /** * The query type of Elasticsearch®. * - * Possible values: simple, vector + * Possible values: "simple", "vector" */ queryType?: string; /** The embedding dependency for vector search. */ @@ -854,6 +842,29 @@ export interface AzureChatOCREnhancementConfiguration { enabled: boolean; } +/** + * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + * mode. + */ +export interface ChatCompletionsResponseFormatParent { + type: string; +} + +/** + * The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response + * content that adheres to a specific schema. + */ +export interface ChatCompletionsTextResponseFormat extends ChatCompletionsResponseFormatParent { + /** The discriminated object type, which is always 'text' for this format. */ + type: "text"; +} + +/** A response format for Chat Completions that restricts responses to emitting valid JSON objects. */ +export interface ChatCompletionsJsonResponseFormat extends ChatCompletionsResponseFormatParent { + /** The discriminated object type, which is always 'json_object' for this format. */ + type: "json_object"; +} + /** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ export interface ChatCompletionsToolDefinitionParent { type: string; @@ -877,11 +888,8 @@ export interface ChatCompletionsNamedFunctionToolSelection extends ChatCompletionsNamedToolSelectionParent { /** The object type, which is always 'function'. */ type: "function"; - /** Specifies a tool the model should use. Used to force the model to call a specific function. */ - function: { - /** The name of the function that should be called. */ - name: string; - }; + /** The name of the function that should be called. */ + name: string; } /** Represents the request data used to generate images. */ @@ -904,27 +912,27 @@ export interface ImageGenerationOptions { * Dall-e-2 models support 256x256, 512x512, or 1024x1024. * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. * - * Possible values: 256x256, 512x512, 1024x1024, 1792x1024, 1024x1792 + * Possible values: "256x256", "512x512", "1024x1024", "1792x1024", "1024x1792" */ size?: string; /** * The format in which image generation response items should be presented. * - * Possible values: url, b64_json + * Possible values: "url", "b64_json" */ response_format?: string; /** * The desired image generation quality level to use. * Only configurable with dall-e-3 models. * - * Possible values: standard, hd + * Possible values: "standard", "hd" */ quality?: string; /** * The desired image generation style to use. * Only configurable with dall-e-3 models. * - * Possible values: natural, vivid + * Possible values: "natural", "vivid" */ style?: string; /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ @@ -960,24 +968,31 @@ export interface EmbeddingsOptions { /** An abstract representation of a chat message as provided in a request. */ export type ChatRequestMessage = + | ChatRequestMessageParent | ChatRequestSystemMessage | ChatRequestUserMessage | ChatRequestAssistantMessage | ChatRequestToolMessage | ChatRequestFunctionMessage; /** An abstract representation of a structured content item within a chat message. */ -export type ChatMessageContentItem = ChatMessageTextContentItem | ChatMessageImageContentItem; +export type ChatMessageContentItem = + | ChatMessageContentItemParent + | ChatMessageTextContentItem + | ChatMessageImageContentItem; /** * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested * chat completion. */ -export type ChatCompletionsToolCall = ChatCompletionsFunctionToolCall; +export type ChatCompletionsToolCall = + | ChatCompletionsToolCallParent + | ChatCompletionsFunctionToolCall; /** * A representation of configuration data for a single Azure OpenAI chat extension. This will be used by a chat * completions request that should use Azure OpenAI chat extensions to augment the response behavior. * The use of this configuration is compatible only with Azure OpenAI. */ export type AzureChatExtensionConfiguration = + | AzureChatExtensionConfigurationParent | AzureCognitiveSearchChatExtensionConfiguration | AzureMachineLearningIndexChatExtensionConfiguration | AzureCosmosDBChatExtensionConfiguration @@ -985,6 +1000,7 @@ export type AzureChatExtensionConfiguration = | PineconeChatExtensionConfiguration; /** The authentication options for Azure OpenAI On Your Data. */ export type OnYourDataAuthenticationOptions = + | OnYourDataAuthenticationOptionsParent | OnYourDataApiKeyAuthenticationOptions | OnYourDataConnectionStringAuthenticationOptions | OnYourDataKeyAndKeyIdAuthenticationOptions @@ -992,28 +1008,23 @@ export type OnYourDataAuthenticationOptions = | OnYourDataUserAssignedManagedIdentityAuthenticationOptions; /** An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. */ export type OnYourDataVectorizationSource = + | OnYourDataVectorizationSourceParent | OnYourDataEndpointVectorizationSource | OnYourDataDeploymentNameVectorizationSource | OnYourDataModelIdVectorizationSource; -/** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ -export type ChatCompletionsToolDefinition = ChatCompletionsFunctionToolDefinition; -/** An abstract representation of an explicit, named tool selection to use for a chat completions request. */ -export type ChatCompletionsNamedToolSelection = ChatCompletionsNamedFunctionToolSelection; - -/** The standard Chat Completions response format that can freely generate text and is not guaranteed to produce response -content that adheres to a specific schema. */ -export interface ChatCompletionsTextResponseFormat { - /** The object type, which is always 'text' for this object. */ - type: "text"; -} -/** A response format for Chat Completions that restricts responses to emitting valid JSON objects. +/** + * An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + * mode. */ -export interface ChatCompletionsJsonResponseFormat { - /** The object type, which is always 'json_object' for this object. */ - type: "json_object"; -} - -/** The valid response formats Chat Completions can provide. Used to enable JSON mode. */ export type ChatCompletionsResponseFormat = + | ChatCompletionsResponseFormatParent | ChatCompletionsTextResponseFormat | ChatCompletionsJsonResponseFormat; +/** An abstract representation of a tool that can be used by the model to improve a chat completions response. */ +export type ChatCompletionsToolDefinition = + | ChatCompletionsToolDefinitionParent + | ChatCompletionsFunctionToolDefinition; +/** An abstract representation of an explicit, named tool selection to use for a chat completions request. */ +export type ChatCompletionsNamedToolSelection = + | ChatCompletionsNamedToolSelectionParent + | ChatCompletionsNamedFunctionToolSelection; diff --git a/sdk/openai/openai/src/rest/openAIClient.ts b/sdk/openai/openai/src/rest/openAIClient.ts index dfdbcb67fdcf..b1c622ad7ee8 100644 --- a/sdk/openai/openai/src/rest/openAIClient.ts +++ b/sdk/openai/openai/src/rest/openAIClient.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { getClient, ClientOptions } from "@azure-rest/core-client"; import { logger } from "../logger.js"; import { TokenCredential, KeyCredential } from "@azure/core-auth"; diff --git a/sdk/openai/openai/src/rest/outputModels.ts b/sdk/openai/openai/src/rest/outputModels.ts index c215a423c7b8..c7d09af7c6e3 100644 --- a/sdk/openai/openai/src/rest/outputModels.ts +++ b/sdk/openai/openai/src/rest/outputModels.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { ErrorModel } from "@azure-rest/core-client"; /** A specific deployment */ @@ -24,7 +16,7 @@ export interface AudioTranscriptionOutput { /** * The label that describes which operation type generated the accompanying response data. * - * Possible values: transcribe, translate + * Possible values: "transcribe", "translate" */ task?: string; /** @@ -79,7 +71,7 @@ export interface AudioTranslationOutput { /** * The label that describes which operation type generated the accompanying response data. * - * Possible values: transcribe, translate + * Possible values: "transcribe", "translate" */ task?: string; /** @@ -208,7 +200,7 @@ export interface ContentFilterResultOutput { /** * Ratings for the intensity and risk level of filtered content. * - * Possible values: safe, low, medium, high + * Possible values: "safe", "low", "medium", "high" */ severity: string; /** A value indicating whether or not the content has been filtered. */ @@ -390,12 +382,12 @@ export interface ChatCompletionsOutput { * Content filtering results for zero or more prompts in the request. In a streaming request, * results for different prompts may arrive at different times or in different orders. */ - prompt_filter_results: Array; + prompt_filter_results?: Array; /** * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that * might impact determinism. */ - system_fingerprint: string; + system_fingerprint?: string; /** Usage information for tokens processed and generated as part of this completions operation. */ usage: CompletionsUsageOutput; } @@ -438,7 +430,7 @@ export interface ChatResponseMessageOutput { /** * The chat role associated with the message. * - * Possible values: system, assistant, user, function, tool + * Possible values: "system", "assistant", "user", "function", "tool" */ role: string; /** The content of the message. */ @@ -543,6 +535,53 @@ export interface AzureGroundingEnhancementCoordinatePointOutput { y: number; } +/** Represents the request data used to generate images. */ +export interface ImageGenerationOptionsOutput { + /** + * The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be + * inferred as a default. + */ + model?: string; + /** A description of the desired images. */ + prompt: string; + /** + * The number of images to generate. + * Dall-e-2 models support values between 1 and 10. + * Dall-e-3 models only support a value of 1. + */ + n?: number; + /** + * The desired dimensions for generated images. + * Dall-e-2 models support 256x256, 512x512, or 1024x1024. + * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. + * + * Possible values: "256x256", "512x512", "1024x1024", "1792x1024", "1024x1792" + */ + size?: string; + /** + * The format in which image generation response items should be presented. + * + * Possible values: "url", "b64_json" + */ + response_format?: string; + /** + * The desired image generation quality level to use. + * Only configurable with dall-e-3 models. + * + * Possible values: "standard", "hd" + */ + quality?: string; + /** + * The desired image generation style to use. + * Only configurable with dall-e-3 models. + * + * Possible values: "natural", "vivid" + */ + style?: string; + /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ + user?: string; +} + /** The result of a successful image generation operation. */ export interface ImageGenerationsOutput { /** @@ -614,64 +653,22 @@ export interface BatchImageGenerationOperationResponseOutput { /** * The status of the operation * - * Possible values: notRunning, running, succeeded, canceled, failed + * Possible values: "notRunning", "running", "succeeded", "canceled", "failed" */ status: string; /** The error if the operation failed. */ error?: ErrorModel; } -/** Represents the request data used to generate images. */ -export interface ImageGenerationOptionsOutput { - /** - * The model name or Azure OpenAI model deployment name to use for image generation. If not specified, dall-e-2 will be - * inferred as a default. - */ - model?: string; - /** A description of the desired images. */ - prompt: string; - /** - * The number of images to generate. - * Dall-e-2 models support values between 1 and 10. - * Dall-e-3 models only support a value of 1. - */ - n?: number; - /** - * The desired dimensions for generated images. - * Dall-e-2 models support 256x256, 512x512, or 1024x1024. - * Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. - * - * Possible values: 256x256, 512x512, 1024x1024, 1792x1024, 1024x1792 - */ - size?: string; - /** - * The format in which image generation response items should be presented. - * - * Possible values: url, b64_json - */ - response_format?: string; - /** - * The desired image generation quality level to use. - * Only configurable with dall-e-3 models. - * - * Possible values: standard, hd - */ - quality?: string; - /** - * The desired image generation style to use. - * Only configurable with dall-e-3 models. - * - * Possible values: natural, vivid - */ - style?: string; - /** A unique identifier representing your end-user, which can help to monitor and detect abuse. */ - user?: string; -} - /** * An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested * chat completion. */ -export type ChatCompletionsToolCallOutput = ChatCompletionsFunctionToolCallOutput; +export type ChatCompletionsToolCallOutput = + | ChatCompletionsToolCallOutputParent + | ChatCompletionsFunctionToolCallOutput; /** An abstract representation of structured information about why a chat completions response terminated. */ -export type ChatFinishDetailsOutput = StopFinishDetailsOutput | MaxTokensFinishDetailsOutput; +export type ChatFinishDetailsOutput = + | ChatFinishDetailsOutputParent + | StopFinishDetailsOutput + | MaxTokensFinishDetailsOutput; diff --git a/sdk/openai/openai/src/rest/parameters.ts b/sdk/openai/openai/src/rest/parameters.ts index 79f0fe8d98e8..3d0c994d76f0 100644 --- a/sdk/openai/openai/src/rest/parameters.ts +++ b/sdk/openai/openai/src/rest/parameters.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { RequestParameters } from "@azure-rest/core-client"; import { AudioTranscriptionOptions, diff --git a/sdk/openai/openai/src/rest/responses.ts b/sdk/openai/openai/src/rest/responses.ts index d7b35913a1c2..c7087c38d32b 100644 --- a/sdk/openai/openai/src/rest/responses.ts +++ b/sdk/openai/openai/src/rest/responses.ts @@ -1,14 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -/** - * THIS IS AN AUTO-GENERATED FILE - DO NOT EDIT! - * - * Any changes you make here may be lost. - * - * If you need to make changes, please do so in the original source file, \{project-root\}/sources/custom - */ - import { RawHttpHeaders } from "@azure/core-rest-pipeline"; import { HttpResponse, ErrorResponse } from "@azure-rest/core-client"; import { diff --git a/sdk/openai/openai/src/utils/serializeUtil.ts b/sdk/openai/openai/src/utils/serializeUtil.ts new file mode 100644 index 000000000000..7483fd56cf74 --- /dev/null +++ b/sdk/openai/openai/src/utils/serializeUtil.ts @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +import { + ChatRequestUserMessage as ChatRequestUserMessageRest, + ChatRequestAssistantMessage as ChatRequestAssistantMessageRest, + ChatRequestToolMessage as ChatRequestToolMessageRest, + ChatRequestMessage as ChatRequestMessageRest, + ChatMessageImageContentItem as ChatMessageImageContentItemRest, + ChatMessageContentItem as ChatMessageContentItemRest, +} from "../rest/index.js"; +import { + ChatRequestUserMessage, + ChatRequestAssistantMessage, + ChatRequestToolMessage, + ChatRequestMessageUnion, + ChatMessageImageContentItem, + ChatMessageContentItemUnion, +} from "../models/models.js"; +import { snakeCaseKeys } from "../api/util.js"; + +/** serialize function for ChatRequestUserMessage */ +function serializeChatRequestUserMessage(obj: ChatRequestUserMessage): ChatRequestUserMessageRest { + return { + role: obj["role"], + content: + typeof obj["content"] === "string" + ? obj["content"] + : obj["content"].map(serializeChatRequestContentItemUnion), + name: obj["name"], + }; +} + +/** serialize function for ChatMessageImageContentItem */ +function serializeChatRequestContentItemUnion( + obj: ChatMessageContentItemUnion, +): ChatMessageContentItemRest { + switch (obj.type) { + case "image_url": + return serializeChatMessageImageContentItem(obj as ChatMessageImageContentItem); + default: + return obj; + } +} +/** serialize function for ChatRequestAssistantMessage */ +function serializeChatRequestAssistantMessage( + obj: ChatRequestAssistantMessage, +): ChatRequestAssistantMessageRest { + if (obj.content === undefined) { + obj.content = null; + } + const { functionCall, toolCalls, ...rest } = obj; + return { + ...snakeCaseKeys(rest), + ...(!toolCalls || toolCalls.length === 0 ? {} : { tool_calls: toolCalls }), + ...(functionCall ? { function_call: functionCall } : {}), + }; +} + +/** serialize function for ChatRequestToolMessage */ +function serializeChatRequestToolMessage(obj: ChatRequestToolMessage): ChatRequestToolMessageRest { + return { + role: obj["role"], + content: obj["content"], + tool_call_id: obj["toolCallId"], + }; +} + +/** serialize function for ChatRequestMessageUnion */ +export function serializeChatRequestMessageUnion( + obj: ChatRequestMessageUnion, +): ChatRequestMessageRest { + switch (obj.role) { + case "user": + return serializeChatRequestUserMessage(obj as ChatRequestUserMessage); + case "assistant": + return serializeChatRequestAssistantMessage(obj as ChatRequestAssistantMessage); + case "tool": + return serializeChatRequestToolMessage(obj as ChatRequestToolMessage); + default: + return obj; + } +} + +/** serialize function for ChatMessageImageContentItem */ +function serializeChatMessageImageContentItem( + obj: ChatMessageImageContentItem, +): ChatMessageImageContentItemRest { + return { + type: obj["type"], + image_url: { url: obj.imageUrl["url"], detail: obj.imageUrl["detail"] }, + }; +} + +/** serialize function for ChatMessageContentItemUnion */ +export function serializeChatMessageContentItemUnion( + obj: ChatMessageContentItemUnion, +): ChatMessageContentItemRest { + switch (obj.type) { + case "image_url": + return serializeChatMessageImageContentItem(obj as ChatMessageImageContentItem); + default: + return obj; + } +} diff --git a/sdk/openai/openai/test/internal/deserializer.spec.ts b/sdk/openai/openai/test/internal/deserializer.spec.ts index 4dcf2edc1194..c173bee6c807 100644 --- a/sdk/openai/openai/test/internal/deserializer.spec.ts +++ b/sdk/openai/openai/test/internal/deserializer.spec.ts @@ -2,10 +2,7 @@ // Licensed under the MIT license. import { assert } from "@azure/test-utils"; -import { - getChatCompletionsResult, - getCompletionsResult, -} from "../../src/api/client/openAIClient/deserializers.js"; +import { getChatCompletionsResult, getCompletionsResult } from "../../src/api/operations.js"; const created = new Date("2022-01-01T00:00:00.000Z").getTime(); diff --git a/sdk/openai/openai/test/public/completions.spec.ts b/sdk/openai/openai/test/public/completions.spec.ts index 963af5a7d3e7..82db6c4dd84a 100644 --- a/sdk/openai/openai/test/public/completions.spec.ts +++ b/sdk/openai/openai/test/public/completions.spec.ts @@ -20,7 +20,12 @@ import { updateWithSucceeded, withDeployments, } from "./utils/utils.js"; -import { ChatRequestMessage, OpenAIClient } from "../../src/index.js"; +import { + ChatCompletionsFunctionToolCall, + ChatRequestMessage, + ChatRequestMessageUnion, + OpenAIClient, +} from "../../src/index.js"; import { AuthMethod } from "./types.js"; describe("OpenAI", function () { @@ -213,7 +218,7 @@ describe("OpenAI", function () { chatCompletionModels, ), async (deploymentName) => { - const weatherMessages: ChatRequestMessage[] = [ + const weatherMessages: ChatRequestMessageUnion[] = [ { role: "user", content: "What's the weather like in Boston?" }, ]; const result = await client.getChatCompletions(deploymentName, weatherMessages, { @@ -339,7 +344,9 @@ describe("OpenAI", function () { (res) => { assertChatCompletions(res, { functions: true }); assert.isDefined(res.choices[0].message?.toolCalls); - const argument = res.choices[0].message?.toolCalls[0].function.arguments; + const argument = ( + res.choices[0].message?.toolCalls[0] as ChatCompletionsFunctionToolCall + ).function.arguments; assert.isTrue(argument?.includes("assetName")); }, ), @@ -406,7 +413,10 @@ describe("OpenAI", function () { deploymentName, [{ role: "user", content: "What's the weather like in Boston?" }], { - toolChoice: { type: "function", function: { name: getCurrentWeather.name } }, + toolChoice: { + type: "function", + function: { name: getCurrentWeather.name }, + } as any, tools: [ { type: "function", function: getCurrentWeather }, { @@ -436,7 +446,8 @@ describe("OpenAI", function () { (res) => { assertChatCompletions(res, { functions: true }); assert.equal( - res.choices[0].message?.toolCalls[0].function.name, + (res.choices[0].message?.toolCalls[0] as ChatCompletionsFunctionToolCall) + .function.name, getCurrentWeather.name, ); assert.isUndefined(res.choices[0].message?.functionCall); diff --git a/sdk/openai/openai/test/public/samples.spec.ts b/sdk/openai/openai/test/public/samples.spec.ts index 959ce050340e..64f419fd79c7 100644 --- a/sdk/openai/openai/test/public/samples.spec.ts +++ b/sdk/openai/openai/test/public/samples.spec.ts @@ -7,7 +7,7 @@ import { Context } from "mocha"; import { ChatCompletionsFunctionToolCall, ChatRequestAssistantMessage, - ChatRequestMessage, + ChatRequestMessageUnion, ChatRequestToolMessage, OpenAIClient, } from "../../src/index.js"; @@ -31,7 +31,7 @@ describe("README samples", () => { it("Generate Chatbot Response", async function () { const deploymentId = "gpt-35-turbo"; - const messages: ChatRequestMessage[] = [ + const messages: ChatRequestMessageUnion[] = [ { role: "system", content: "You are a helpful assistant. You will talk like a pirate." }, { role: "user", content: "Can you help me?" }, { role: "assistant", content: "Arrrr! Of course, me hearty! What can I do for ye?" }, @@ -146,7 +146,7 @@ describe("README samples", () => { const choice = result.choices[0]; const responseMessage = choice.message; if (responseMessage?.role === "assistant") { - const requestedToolCalls = responseMessage?.toolCalls; + const requestedToolCalls = responseMessage?.toolCalls as ChatCompletionsFunctionToolCall[]; if (requestedToolCalls?.length) { const toolCallResolutionMessages = [ ...messages, @@ -188,7 +188,7 @@ describe("README samples", () => { const url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"; const deploymentName = "gpt-4-1106-preview"; - const messages: ChatRequestMessage[] = [ + const messages: ChatRequestMessageUnion[] = [ { role: "user", content: [ diff --git a/sdk/openai/openai/test/public/utils/asserts.ts b/sdk/openai/openai/test/public/utils/asserts.ts index 4820838c2c18..6f41f1b6e3c3 100644 --- a/sdk/openai/openai/test/public/utils/asserts.ts +++ b/sdk/openai/openai/test/public/utils/asserts.ts @@ -15,7 +15,8 @@ import { AzureGroundingEnhancementLineSpan, ChatChoice, ChatCompletions, - ChatCompletionsToolCall, + ChatCompletionsFunctionToolCall, + ChatCompletionsToolCallUnion, ChatFinishDetails, ChatResponseMessage, Choice, @@ -32,6 +33,7 @@ import { ContentFilterResultsForPrompt, FunctionCall, ImageGenerations, + StopFinishDetails, } from "../../../src/index.js"; import { Recorder } from "@azure-tools/test-recorder"; import { get } from "./utils.js"; @@ -175,7 +177,7 @@ function assertFunctionCall( } function assertToolCall( - functionCall: ChatCompletionsToolCall, + functionCall: ChatCompletionsToolCallUnion, { stream }: ChatCompletionTestOptions, ): void { assertIf(!stream, functionCall.type, assert.isString); @@ -183,7 +185,7 @@ function assertToolCall( assertIf(Boolean(stream), functionCall.index, assert.isNumber); switch (functionCall.type) { case "function": - assertFunctionCall(functionCall.function, { stream }); + assertFunctionCall((functionCall as ChatCompletionsFunctionToolCall).function, { stream }); break; } } @@ -218,7 +220,7 @@ function assertChatFinishDetails(val: ChatFinishDetails): void { case "max_tokens": break; case "stop": { - assert.isString(val.stop); + assert.isString((val as StopFinishDetails).stop); break; } } diff --git a/sdk/openai/openai/tsconfig.json b/sdk/openai/openai/tsconfig.json index f68a1f924e6f..233a0a863d4a 100644 --- a/sdk/openai/openai/tsconfig.json +++ b/sdk/openai/openai/tsconfig.json @@ -10,5 +10,5 @@ "rootDir": "." }, "ts-node": { "esm": true }, - "include": ["src/**/*.ts", "sources/**/*.ts", "test/**/*.ts", "samples-dev/**/*.ts"] + "include": ["src/**/*.ts", "test/**/*.ts", "samples-dev/**/*.ts"] } diff --git a/sdk/openai/openai/tsp-location.yaml b/sdk/openai/openai/tsp-location.yaml index 2576624cdb1c..5f6700b7727f 100644 --- a/sdk/openai/openai/tsp-location.yaml +++ b/sdk/openai/openai/tsp-location.yaml @@ -1,3 +1,3 @@ directory: specification/cognitiveservices/OpenAI.Inference -commit: 3e2daf2e75343c466d3602222ac2371a5a91bea2 +commit: 2aaf1e85a93733499230175b1a8a8b26af0cdf4d repo: Azure/azure-rest-api-specs