From be4d2dbb70345c56998d029d358733a7d69c1d14 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Wed, 2 Apr 2025 23:03:33 +0000 Subject: [PATCH] CodeGen from PR 33679 in Azure/azure-rest-api-specs Merge 324bec9812c45197ad9d65174af0f3ee87325ce4 into 8c02b46beae05085b18570498e7c6b00c31ddea5 --- .../Microsoft.VoiceServices.Provisioning.sln | 50 + .../AccountResource.Serialization.cs | 215 + .../src/Generated/AccountResource.cs | 93 + .../AccountServiceDetails.Serialization.cs | 228 + .../src/Generated/AccountServiceDetails.cs | 85 + .../src/Generated/Accounts.cs | 2036 +++ ...lProtectionAccountDetails.Serialization.cs | 158 + ...ureOperatorCallProtectionAccountDetails.cs | 76 + ...llProtectionNumberDetails.Serialization.cs | 143 + ...zureOperatorCallProtectionNumberDetails.cs | 72 + .../Generated/BatchNumbers.Serialization.cs | 153 + .../src/Generated/BatchNumbers.cs | 76 + .../BatchNumbersDelete.Serialization.cs | 153 + .../src/Generated/BatchNumbersDelete.cs | 76 + .../Generated/ContactDetails.Serialization.cs | 196 + .../src/Generated/ContactDetails.cs | 81 + .../CustomerRelationship.Serialization.cs | 172 + .../src/Generated/CustomerRelationship.cs | 73 + .../src/Generated/Docs/Accounts.xml | 973 ++ .../Docs/TeamsRequestsForInformation.xml | 155 + .../Generated/Docs/VoiceServicesClient.xml | 65 + .../src/Generated/Internal/Argument.cs | 129 + .../Internal/ChangeTrackingDictionary.cs | 167 + .../Generated/Internal/ChangeTrackingList.cs | 153 + .../Internal/ModelSerializationExtensions.cs | 399 + .../src/Generated/Internal/Optional.cs | 51 + .../Internal/Utf8JsonRequestContent.cs | 55 + .../src/Generated/Location.Serialization.cs | 212 + .../src/Generated/Location.cs | 85 + ...icesProvisioningClientBuilderExtensions.cs | 35 + ...ftVoiceServicesProvisioningModelFactory.cs | 365 + .../NumberConfiguration.Serialization.cs | 146 + .../src/Generated/NumberConfiguration.cs | 65 + .../NumberIdentifier.Serialization.cs | 143 + .../src/Generated/NumberIdentifier.cs | 75 + .../NumberIdentifiers.Serialization.cs | 153 + .../src/Generated/NumberIdentifiers.cs | 76 + .../Generated/NumberResource.Serialization.cs | 221 + .../src/Generated/NumberResource.cs | 103 + .../NumberServiceDetails.Serialization.cs | 216 + .../src/Generated/NumberServiceDetails.cs | 81 + ...estForInformationResource.Serialization.cs | 354 + .../RequestForInformationResource.cs | 117 + .../Generated/ServiceProvisioningStatus.cs | 54 + ...eamsAvailableCapabilities.Serialization.cs | 156 + .../Generated/TeamsAvailableCapabilities.cs | 66 + .../TeamsCapabilityPlan.Serialization.cs | 250 + .../src/Generated/TeamsCapabilityPlan.cs | 88 + .../TeamsCapabilityPlans.Serialization.cs | 156 + .../src/Generated/TeamsCapabilityPlans.cs | 66 + ...TeamsCivicAddressResource.Serialization.cs | 430 + .../Generated/TeamsCivicAddressResource.cs | 154 + .../src/Generated/TeamsConsentStatus.cs | 54 + ...irectRoutingAccountConfig.Serialization.cs | 159 + .../TeamsDirectRoutingAccountConfig.cs | 88 + ...rectRoutingAccountDetails.Serialization.cs | 198 + .../TeamsDirectRoutingAccountDetails.cs | 90 + ...irectRoutingNumberDetails.Serialization.cs | 143 + .../TeamsDirectRoutingNumberDetails.cs | 72 + ...irectRoutingSubdomainProvisioningStatus.cs | 54 + ...ectRoutingSubdomainTokens.Serialization.cs | 151 + .../TeamsDirectRoutingSubdomainTokens.cs | 82 + ...atorConnectAccountDetails.Serialization.cs | 166 + .../TeamsOperatorConnectAccountDetails.cs | 82 + ...eratorConnectNumberConfig.Serialization.cs | 294 + .../TeamsOperatorConnectNumberConfig.cs | 114 + ...ratorConnectNumberDetails.Serialization.cs | 173 + .../TeamsOperatorConnectNumberDetails.cs | 80 + ...PhoneMobileAccountDetails.Serialization.cs | 166 + .../TeamsPhoneMobileAccountDetails.cs | 82 + ...msPhoneMobileNumberConfig.Serialization.cs | 294 + .../Generated/TeamsPhoneMobileNumberConfig.cs | 114 + ...sPhoneMobileNumberDetails.Serialization.cs | 173 + .../TeamsPhoneMobileNumberDetails.cs | 80 + .../Generated/TeamsRequestsForInformation.cs | 447 + .../TelephoneNumberAssignmentStatus.cs | 51 + .../src/Generated/ValidationStatus.cs | 51 + .../src/Generated/VoiceServicesClient.cs | 234 + .../Generated/VoiceServicesClientOptions.cs | 37 + ...loudPeeringAccountDetails.Serialization.cs | 166 + .../ZoomPhoneCloudPeeringAccountDetails.cs | 82 + ...CloudPeeringNumberDetails.Serialization.cs | 143 + .../ZoomPhoneCloudPeeringNumberDetails.cs | 72 + ...icrosoft.VoiceServices.Provisioning.csproj | 19 + .../src/Properties/AssemblyInfo.cs | 6 + .../Generated/Samples/Samples_Accounts.cs | 988 ++ .../Samples_TeamsRequestsForInformation.cs | 170 + .../Samples/Samples_VoiceServicesClient.cs | 80 + ...ft.VoiceServices.Provisioning.Tests.csproj | 19 + .../tsp-location.yaml | 4 + .../azure.ApiCenter/Configuration.json | 12 + .../azure.ApiCenter/tsp-location.yaml | 4 + .../azure.ApiCenter/tspCodeModel.json | 8146 ++++++++++ .../Configuration.json | 12 + .../src/autorest.md | 55 - .../tsp-location.yaml | 4 + .../tspCodeModel.json | 13365 ++++++++++++++++ .../LiveMetrics/LiveMetrics.sln | 50 + .../src/Generated/AggregationType.cs | 57 + ...lectionConfigurationError.Serialization.cs | 177 + .../Generated/CollectionConfigurationError.cs | 96 + .../CollectionConfigurationErrorType.cs | 84 + ...llectionConfigurationInfo.Serialization.cs | 194 + .../Generated/CollectionConfigurationInfo.cs | 94 + .../DerivedMetricInfo.Serialization.cs | 200 + .../src/Generated/DerivedMetricInfo.cs | 109 + .../src/Generated/Docs/LiveMetricsClient.xml | 439 + ...ilterConjunctionGroupInfo.Serialization.cs | 151 + .../DocumentFilterConjunctionGroupInfo.cs | 81 + .../DocumentIngress.Serialization.cs | 158 + .../src/Generated/DocumentIngress.cs | 79 + .../DocumentStreamInfo.Serialization.cs | 161 + .../src/Generated/DocumentStreamInfo.cs | 83 + .../LiveMetrics/src/Generated/DocumentType.cs | 63 + .../src/Generated/Event.Serialization.cs | 168 + .../LiveMetrics/src/Generated/Event.cs | 36 + .../src/Generated/Exception.Serialization.cs | 185 + .../LiveMetrics/src/Generated/Exception.cs | 40 + ...lterConjunctionGroupInfo.Serialization.cs} | 65 +- .../Generated/FilterConjunctionGroupInfo.cs | 76 + .../src/Generated/FilterInfo.Serialization.cs | 159 + .../LiveMetrics/src/Generated/FilterInfo.cs | 88 + .../src/Generated/Internal/Argument.cs | 129 + .../Internal/ChangeTrackingDictionary.cs | 167 + .../Generated/Internal/ChangeTrackingList.cs | 153 + .../Internal/ModelSerializationExtensions.cs | 399 + .../src/Generated/Internal/Optional.cs | 51 + .../Internal/RequestContentHelper.cs} | 58 +- .../Internal/Utf8JsonRequestContent.cs | 55 + .../KeyValuePairStringString.Serialization.cs | 151 + .../src/Generated/KeyValuePairStringString.cs | 82 + .../src/Generated/LiveMetricsClient.cs | 408 + .../LiveMetricsClientBuilderExtensions.cs | 35 + .../src/Generated/LiveMetricsClientOptions.cs | 37 + .../src/Generated/LiveMetricsModelFactory.cs | 148 + .../Generated/MetricPoint.Serialization.cs} | 83 +- .../LiveMetrics/src/Generated/MetricPoint.cs | 87 + .../MonitoringDataPoint.Serialization.cs | 344 + .../src/Generated/MonitoringDataPoint.cs | 157 + .../src/Generated/PredicateType.cs | 69 + .../Generated/ProcessCpuData.Serialization.cs | 151 + .../src/Generated/ProcessCpuData.cs | 81 + .../QuotaConfigurationInfo.Serialization.cs | 166 + .../src/Generated/QuotaConfigurationInfo.cs | 82 + .../RemoteDependency.Serialization.cs | 209 + .../src/Generated/RemoteDependency.cs | 48 + .../src/Generated/Request.Serialization.cs | 213 + .../LiveMetrics/src/Generated/Request.cs | 48 + .../src/Generated/TelemetryType.cs | 66 + .../src/Generated/Trace.Serialization.cs | 168 + .../LiveMetrics/src/Generated/Trace.cs | 36 + .../UnknownDocumentIngress.Serialization.cs | 157 + .../src/Generated/UnknownDocumentIngress.cs | 30 + .../LiveMetrics/src/LiveMetrics.csproj | 19 + .../src/Properties/AssemblyInfo.cs | 6 + .../Samples/Samples_LiveMetricsClient.cs | 454 + .../tests/LiveMetrics.Tests.csproj | 19 + .../LiveMetrics/tsp-location.yaml | 4 + .../tsp-location.yaml | 7 +- .../Azure.Template.Contoso/tsp-location.yaml | 4 + .../tsp-location.yaml | 3 +- .../src/Generated/AIVisionFaceModelFactory.cs | 294 +- .../Generated/AuditLivenessResponseInfo.cs | 87 - .../src/Generated/AuditRequestInfo.cs | 97 - .../AzureAIVisionFaceClientOptions.cs | 5 +- ...ateLivenessSessionContent.Serialization.cs | 30 +- .../Generated/CreateLivenessSessionContent.cs | 12 +- .../Generated/CreateLivenessSessionResult.cs | 82 - ...sWithVerifySessionContent.Serialization.cs | 152 +- .../CreateLivenessWithVerifySessionContent.cs | 42 +- .../CreateLivenessWithVerifySessionResult.cs | 86 - .../src/Generated/Docs/FaceSessionClient.xml | 316 +- .../src/Generated/FaceSessionClient.cs | 935 +- .../src/Generated/FaceSessionStatus.cs | 54 - .../src/Generated/LargeFaceListClient.cs | 2 +- .../src/Generated/LargePersonGroupClient.cs | 2 +- ...venessColorDecisionTarget.Serialization.cs | 142 + ...rget.cs => LivenessColorDecisionTarget.cs} | 37 +- .../LivenessDecisionTargets.Serialization.cs | 142 + .../src/Generated/LivenessDecisionTargets.cs | 75 + .../Generated/LivenessError.Serialization.cs | 158 + .../src/Generated/LivenessError.cs | 89 + .../src/Generated/LivenessModel.cs | 9 +- .../LivenessResponseBody.Serialization.cs | 188 - .../src/Generated/LivenessResponseBody.cs | 77 - .../Generated/LivenessResult.Serialization.cs | 176 + .../src/Generated/LivenessResult.cs | 90 + .../LivenessSession.Serialization.cs | 100 +- .../src/Generated/LivenessSession.cs | 60 +- .../LivenessSessionAttempt.Serialization.cs | 180 + .../src/Generated/LivenessSessionAttempt.cs | 86 + .../Generated/LivenessSessionAuditEntry.cs | 130 - .../src/Generated/LivenessSessionItem.cs | 94 - .../LivenessSessionResults.Serialization.cs | 152 + .../src/Generated/LivenessSessionResults.cs | 76 + ...LivenessWithVerifyOutputs.Serialization.cs | 10 +- .../Generated/LivenessWithVerifyOutputs.cs | 13 +- ...enessWithVerifyReference.Serialization.cs} | 50 +- ...mage.cs => LivenessWithVerifyReference.cs} | 20 +- ...LivenessWithVerifyResult.Serialization.cs} | 134 +- .../src/Generated/LivenessWithVerifyResult.cs | 98 + ...LivenessWithVerifySession.Serialization.cs | 100 +- .../Generated/LivenessWithVerifySession.cs | 60 +- ...sWithVerifySessionAttempt.Serialization.cs | 180 + .../LivenessWithVerifySessionAttempt.cs | 86 + ...sWithVerifySessionResults.Serialization.cs | 170 + .../LivenessWithVerifySessionResults.cs | 83 + .../src/Generated/OperationState.cs | 60 + .../Samples/Samples_FaceSessionClient.cs | 308 +- .../Azure.AI.Vision.Face/tsp-location.yaml | 5 +- .../tsp-location.yaml | 5 +- .../tsp-location.yaml | 7 +- .../tsp-location.yaml | 9 +- .../Microsoft.App.DynamicSessions.sln | 50 + .../src/Generated/CodeExecution.cs | 355 + .../src/Generated/CodeInputType.cs | 54 + .../src/Generated/Docs/CodeExecution.xml | 291 + .../Generated/Docs/SessionResourceFiles.xml | 253 + .../src/Generated/DynamicSessionsClient.cs | 79 + .../Generated/DynamicSessionsClientOptions.cs | 37 + .../Generated/ErrorResponse.Serialization.cs | 143 + .../src/Generated/ErrorResponse.cs | 76 + .../src/Generated/ExecutionType.cs | 51 + .../src/Generated/Internal/Argument.cs | 129 + .../Internal/ChangeTrackingDictionary.cs | 167 + .../Generated/Internal/ChangeTrackingList.cs | 153 + .../Internal/ModelSerializationExtensions.cs | 399 + .../MultipartFormDataRequestContent.cs | 203 + .../src/Generated/Internal/Optional.cs | 51 + .../Internal/Utf8JsonRequestContent.cs | 55 + ...pDynamicSessionsClientBuilderExtensions.cs | 35 + ...MicrosoftAppDynamicSessionsModelFactory.cs | 75 + .../src/Generated/OperationState.cs | 60 + ...ssionCodeExecutionRequest.Serialization.cs | 167 + .../Generated/SessionCodeExecutionRequest.cs | 93 + ...sionCodeExecutionResource.Serialization.cs | 207 + .../Generated/SessionCodeExecutionResource.cs | 99 + ...essionCodeExecutionResult.Serialization.cs | 194 + .../Generated/SessionCodeExecutionResult.cs | 106 + .../SessionResourceFile.Serialization.cs | 191 + .../src/Generated/SessionResourceFile.cs | 96 + .../src/Generated/SessionResourceFiles.cs | 722 + .../Generated/UploadRequest.Serialization.cs | 175 + .../src/Generated/UploadRequest.cs | 76 + .../src/Microsoft.App.DynamicSessions.csproj | 19 + .../src/Properties/AssemblyInfo.cs | 6 + .../Samples/Samples_CodeExecution.cs | 342 + .../Samples/Samples_SessionResourceFiles.cs | 268 + ...Microsoft.App.DynamicSessions.Tests.csproj | 19 + .../tsp-location.yaml | 4 + .../src/Generated/ApiResponseFormat.cs | 54 + .../src/Generated/Assistant.Serialization.cs | 99 +- .../src/Generated/Assistant.cs | 117 +- .../AssistantCreationOptions.Serialization.cs | 103 +- .../src/Generated/AssistantCreationOptions.cs | 92 +- .../src/Generated/AssistantStreamEvent.cs | 134 + .../AssistantThread.Serialization.cs | 28 +- .../src/Generated/AssistantThread.cs | 22 +- ...tantThreadCreationOptions.Serialization.cs | 31 +- .../AssistantThreadCreationOptions.cs | 18 +- ...sistantsApiResponseFormat.Serialization.cs | 138 + .../Generated/AssistantsApiResponseFormat.cs | 70 + ...iResponseFormatJsonObject.Serialization.cs | 130 + .../AssistantsApiResponseFormatJsonObject.cs | 29 + ...iResponseFormatJsonSchema.Serialization.cs | 138 + .../AssistantsApiResponseFormatJsonSchema.cs | 44 + ...ormatJsonSchemaJsonSchema.Serialization.cs | 183 + ...tsApiResponseFormatJsonSchemaJsonSchema.cs | 119 + .../AssistantsApiResponseFormatMode.cs | 48 + ...antsApiResponseFormatText.Serialization.cs | 130 + .../AssistantsApiResponseFormatText.cs | 29 + .../AssistantsApiToolChoiceOptionMode.cs | 51 + .../src/Generated/AssistantsClient.cs | 3301 ++-- .../src/Generated/AssistantsClientOptions.cs | 17 +- .../src/Generated/AssistantsModelFactory.cs | 735 +- ...ssistantsNamedToolChoice.Serialization.cs} | 79 +- .../Generated/AssistantsNamedToolChoice.cs | 76 + .../AssistantsNamedToolChoiceType.cs | 54 + ...deInterpreterToolResource.Serialization.cs | 152 + .../Generated/CodeInterpreterToolResource.cs | 85 + ...CreateAndRunThreadOptions.Serialization.cs | 287 +- .../Generated/CreateAndRunThreadOptions.cs | 178 +- ...preterToolResourceOptions.Serialization.cs | 159 + ...reateCodeInterpreterToolResourceOptions.cs | 66 + ...sourceVectorStoreOptions.Serialization.cs} | 83 +- ...ileSearchToolResourceVectorStoreOptions.cs | 100 + .../CreateRunOptions.Serialization.cs | 247 + .../src/Generated/CreateRunOptions.cs | 173 +- ...reateToolResourcesOptions.Serialization.cs | 171 + .../Generated/CreateToolResourcesOptions.cs | 119 + ...ctorStoreFileBatchRequest.Serialization.cs | 167 + .../CreateVectorStoreFileBatchRequest.cs | 88 + ...ateVectorStoreFileRequest.Serialization.cs | 157 + .../Generated/CreateVectorStoreFileRequest.cs | 87 + .../src/Generated/DoneEvent.cs | 48 + .../src/Generated/ErrorEvent.cs | 48 + .../FileSearchToolCallResult.Serialization.cs | 183 + .../src/Generated/FileSearchToolCallResult.cs | 93 + ...ToolCallResultContentItem.Serialization.cs | 160 + .../FileSearchToolCallResultContentItem.cs | 69 + ...FileSearchToolCallResultContentItemType.cs | 48 + ...FileSearchToolDefinition.Serialization.cs} | 68 +- .../src/Generated/FileSearchToolDefinition.cs | 34 + ...archToolDefinitionDetails.Serialization.cs | 149 + .../FileSearchToolDefinitionDetails.cs | 73 + .../FileSearchToolResource.Serialization.cs | 159 + .../src/Generated/FileSearchToolResource.cs | 72 + .../src/Generated/FileState.cs | 75 + .../Generated/FunctionName.Serialization.cs | 142 + .../src/Generated/FunctionName.cs | 75 + .../src/Generated/IncompleteRunDetails.cs | 51 + ...ternalAssistantFileDeletionStatusObject.cs | 48 - .../InternalMessageImageFileDetails.cs | 4 +- ...nternalMessageTextDetails.Serialization.cs | 2 +- .../Generated/InternalMessageTextDetails.cs | 8 +- .../InternalMessageTextFileCitationDetails.cs | 6 +- .../InternalMessageTextFilePathDetails.cs | 4 +- .../MessageAttachment.Serialization.cs | 179 + .../src/Generated/MessageAttachment.cs | 120 + .../Generated/MessageDelta.Serialization.cs | 160 + .../src/Generated/MessageDelta.cs | 94 + .../MessageDeltaChunk.Serialization.cs | 158 + .../{MessageFile.cs => MessageDeltaChunk.cs} | 48 +- .../src/Generated/MessageDeltaChunkObject.cs | 48 + .../MessageDeltaContent.Serialization.cs | 136 + .../src/Generated/MessageDeltaContent.cs | 80 + ...sageDeltaImageFileContent.Serialization.cs | 147 + .../Generated/MessageDeltaImageFileContent.cs | 41 + ...ltaImageFileContentObject.Serialization.cs | 145 + .../MessageDeltaImageFileContentObject.cs | 65 + ...essageDeltaTextAnnotation.Serialization.cs | 136 + .../Generated/MessageDeltaTextAnnotation.cs | 80 + .../MessageDeltaTextContent.Serialization.cs | 170 + .../src/Generated/MessageDeltaTextContent.cs | 78 + ...ageDeltaTextContentObject.Serialization.cs | 147 + .../MessageDeltaTextContentObject.cs | 41 + ...extFileCitationAnnotation.Serialization.cs | 156 + .../MessageDeltaTextFileCitationAnnotation.cs | 69 + ...eCitationAnnotationObject.Serialization.cs | 195 + ...geDeltaTextFileCitationAnnotationObject.cs | 53 + ...ltaTextFilePathAnnotation.Serialization.cs | 145 + .../MessageDeltaTextFilePathAnnotation.cs | 65 + ...tFilePathAnnotationObject.Serialization.cs | 195 + ...essageDeltaTextFilePathAnnotationObject.cs | 53 + .../src/Generated/MessageImageFileContent.cs | 2 +- .../MessageIncompleteDetails.Serialization.cs | 142 + .../src/Generated/MessageIncompleteDetails.cs | 72 + .../MessageIncompleteDetailsReason.cs | 60 + .../src/Generated/MessageStatus.cs | 54 + .../src/Generated/MessageStreamEvent.cs | 60 + .../MessageTextAnnotation.Serialization.cs | 4 - .../src/Generated/MessageTextAnnotation.cs | 18 +- .../src/Generated/MessageTextContent.cs | 2 +- ...extFileCitationAnnotation.Serialization.cs | 44 +- .../MessageTextFileCitationAnnotation.cs | 22 +- ...ageTextFilePathAnnotation.Serialization.cs | 44 +- .../MessageTextFilePathAnnotation.cs | 16 +- .../src/Generated/OpenAIFile.Serialization.cs | 28 + .../src/Generated/OpenAIFile.cs | 10 +- .../src/Generated/OpenAIFilePurpose.cs | 9 + ...OpenAIPageableListOfAssistantFileObject.cs | 48 - ...ageableListOfVectorStore.Serialization.cs} | 52 +- ....cs => OpenAIPageableListOfVectorStore.cs} | 18 +- ...bleListOfVectorStoreFile.Serialization.cs} | 52 +- ...=> OpenAIPageableListOfVectorStoreFile.cs} | 18 +- ...enAIPageableListOfVectorStoreFileObject.cs | 48 + ... OpenAIPageableListOfVectorStoreObject.cs} | 26 +- .../src/Generated/RetrievalToolDefinition.cs | 29 - .../RunCompletionUsage.Serialization.cs | 158 + .../src/Generated/RunCompletionUsage.cs | 84 + .../src/Generated/RunIncludes.cs | 48 + .../src/Generated/RunStep.Serialization.cs | 24 + .../src/Generated/RunStep.cs | 6 +- .../RunStepCompletionUsage.Serialization.cs | 158 + .../src/Generated/RunStepCompletionUsage.cs | 84 + .../Generated/RunStepDelta.Serialization.cs | 149 + .../src/Generated/RunStepDelta.cs | 73 + .../RunStepDeltaChunk.Serialization.cs | 158 + .../src/Generated/RunStepDeltaChunk.cs | 87 + .../src/Generated/RunStepDeltaChunkObject.cs | 48 + ...terpreterDetailItemObject.Serialization.cs | 170 + ...tepDeltaCodeInterpreterDetailItemObject.cs | 82 + ...odeInterpreterImageOutput.Serialization.cs | 147 + .../RunStepDeltaCodeInterpreterImageOutput.cs | 41 + ...erpreterImageOutputObject.Serialization.cs | 145 + ...epDeltaCodeInterpreterImageOutputObject.cs | 65 + ...aCodeInterpreterLogOutput.Serialization.cs | 143 + .../RunStepDeltaCodeInterpreterLogOutput.cs | 41 + ...eltaCodeInterpreterOutput.Serialization.cs | 136 + .../RunStepDeltaCodeInterpreterOutput.cs | 80 + ...taCodeInterpreterToolCall.Serialization.cs | 153 + .../RunStepDeltaCodeInterpreterToolCall.cs | 46 + .../RunStepDeltaDetail.Serialization.cs | 134 + .../src/Generated/RunStepDeltaDetail.cs | 69 + ...epDeltaFileSearchToolCall.Serialization.cs | 164 + .../RunStepDeltaFileSearchToolCall.cs | 47 + .../RunStepDeltaFunction.Serialization.cs | 179 + .../src/Generated/RunStepDeltaFunction.cs | 73 + ...StepDeltaFunctionToolCall.Serialization.cs | 153 + .../Generated/RunStepDeltaFunctionToolCall.cs | 46 + ...nStepDeltaMessageCreation.Serialization.cs | 141 + .../Generated/RunStepDeltaMessageCreation.cs | 34 + ...eltaMessageCreationObject.Serialization.cs | 145 + .../RunStepDeltaMessageCreationObject.cs | 65 + .../RunStepDeltaToolCall.Serialization.cs | 139 + .../src/Generated/RunStepDeltaToolCall.cs | 89 + ...unStepDeltaToolCallObject.Serialization.cs | 151 + .../Generated/RunStepDeltaToolCallObject.cs | 43 + ...RunStepFileSearchToolCall.Serialization.cs | 150 + .../Generated/RunStepFileSearchToolCall.cs | 51 + .../src/Generated/RunStepRetrievalToolCall.cs | 50 - .../src/Generated/RunStepStreamEvent.cs | 66 + .../RunStepToolCall.Serialization.cs | 2 +- .../src/Generated/RunStepToolCall.cs | 2 +- .../src/Generated/RunStepToolCallDetails.cs | 6 +- .../src/Generated/RunStreamEvent.cs | 72 + ...itToolOutputsToRunRequest.Serialization.cs | 25 +- .../SubmitToolOutputsToRunRequest.cs | 12 +- .../Generated/ThreadMessage.Serialization.cs | 132 +- .../src/Generated/ThreadMessage.cs | 72 +- ... => ThreadMessageOptions.Serialization.cs} | 73 +- ...tionMessage.cs => ThreadMessageOptions.cs} | 62 +- .../src/Generated/ThreadRun.Serialization.cs | 237 +- .../src/Generated/ThreadRun.cs | 161 +- .../src/Generated/ThreadStreamEvent.cs | 48 + .../Generated/ToolDefinition.Serialization.cs | 2 +- .../src/Generated/ToolDefinition.cs | 2 +- .../Generated/ToolResources.Serialization.cs | 164 + .../src/Generated/ToolResources.cs | 73 + .../TruncationObject.Serialization.cs} | 107 +- .../src/Generated/TruncationObject.cs | 91 + .../src/Generated/TruncationStrategy.cs | 51 + ...sistantsApiResponseFormat.Serialization.cs | 130 + .../UnknownAssistantsApiResponseFormat.cs | 28 + ...nknownMessageDeltaContent.Serialization.cs | 132 + .../Generated/UnknownMessageDeltaContent.cs | 29 + ...essageDeltaTextAnnotation.Serialization.cs | 132 + .../UnknownMessageDeltaTextAnnotation.cs | 29 + ...nownMessageTextAnnotation.Serialization.cs | 14 +- .../Generated/UnknownMessageTextAnnotation.cs | 4 +- ...eltaCodeInterpreterOutput.Serialization.cs | 132 + ...nknownRunStepDeltaCodeInterpreterOutput.cs | 29 + ...UnknownRunStepDeltaDetail.Serialization.cs | 126 + .../Generated/UnknownRunStepDeltaDetail.cs | 28 + ...knownRunStepDeltaToolCall.Serialization.cs | 138 + .../Generated/UnknownRunStepDeltaToolCall.cs | 30 + ...reChunkingStrategyRequest.Serialization.cs | 126 + ...knownVectorStoreChunkingStrategyRequest.cs | 28 + ...eChunkingStrategyResponse.Serialization.cs | 126 + ...nownVectorStoreChunkingStrategyResponse.cs | 28 + .../UpdateAssistantOptions.Serialization.cs | 95 +- .../src/Generated/UpdateAssistantOptions.cs | 92 +- ...teAssistantThreadOptions.Serialization.cs} | 67 +- ...est.cs => UpdateAssistantThreadOptions.cs} | 51 +- ...preterToolResourceOptions.Serialization.cs | 159 + ...pdateCodeInterpreterToolResourceOptions.cs | 66 + ...SearchToolResourceOptions.Serialization.cs | 159 + .../UpdateFileSearchToolResourceOptions.cs | 66 + ...pdateToolResourcesOptions.Serialization.cs | 164 + .../Generated/UpdateToolResourcesOptions.cs | 79 + .../src/Generated/UploadFileRequest.cs | 4 +- .../Generated/VectorStore.Serialization.cs | 291 + .../src/Generated/VectorStore.cs | 132 + ...toChunkingStrategyRequest.Serialization.cs | 126 + .../VectorStoreAutoChunkingStrategyRequest.cs | 29 + ...oChunkingStrategyResponse.Serialization.cs | 126 + ...VectorStoreAutoChunkingStrategyResponse.cs | 29 + ...reChunkingStrategyRequest.Serialization.cs | 134 + .../VectorStoreChunkingStrategyRequest.cs | 69 + .../VectorStoreChunkingStrategyRequestType.cs | 51 + ...eChunkingStrategyResponse.Serialization.cs | 134 + .../VectorStoreChunkingStrategyResponse.cs | 69 + ...VectorStoreChunkingStrategyResponseType.cs | 51 + ...ectorStoreDeletionStatus.Serialization.cs} | 46 +- ...Status.cs => VectorStoreDeletionStatus.cs} | 22 +- .../VectorStoreDeletionStatusObject.cs | 48 + ...torStoreExpirationPolicy.Serialization.cs} | 64 +- .../Generated/VectorStoreExpirationPolicy.cs | 78 + .../VectorStoreExpirationPolicyAnchor.cs | 48 + .../VectorStoreFile.Serialization.cs | 219 + .../src/Generated/VectorStoreFile.cs | 139 + .../VectorStoreFileBatch.Serialization.cs | 189 + .../src/Generated/VectorStoreFileBatch.cs | 106 + .../Generated/VectorStoreFileBatchObject.cs | 48 + .../Generated/VectorStoreFileBatchStatus.cs | 57 + .../VectorStoreFileCount.Serialization.cs | 180 + .../src/Generated/VectorStoreFileCount.cs | 96 + ...orStoreFileDeletionStatus.Serialization.cs | 158 + .../VectorStoreFileDeletionStatus.cs | 85 + .../VectorStoreFileDeletionStatusObject.cs | 48 + .../VectorStoreFileError.Serialization.cs | 150 + .../src/Generated/VectorStoreFileError.cs | 81 + .../src/Generated/VectorStoreFileErrorCode.cs | 54 + .../src/Generated/VectorStoreFileObject.cs | 48 + .../src/Generated/VectorStoreFileStatus.cs | 57 + .../Generated/VectorStoreFileStatusFilter.cs | 57 + .../src/Generated/VectorStoreObject.cs | 48 + .../VectorStoreOptions.Serialization.cs | 239 + .../src/Generated/VectorStoreOptions.cs | 91 + ...icChunkingStrategyOptions.Serialization.cs | 150 + ...ectorStoreStaticChunkingStrategyOptions.cs | 87 + ...icChunkingStrategyRequest.Serialization.cs | 134 + ...ectorStoreStaticChunkingStrategyRequest.cs | 44 + ...cChunkingStrategyResponse.Serialization.cs | 134 + ...ctorStoreStaticChunkingStrategyResponse.cs | 44 + .../src/Generated/VectorStoreStatus.cs | 54 + .../VectorStoreUpdateOptions.Serialization.cs | 213 + ...Request.cs => VectorStoreUpdateOptions.cs} | 22 +- .../tsp-location.yaml | 3 +- .../AIOpenAIClientBuilderExtensions.cs | 52 + .../src/Generated/AIOpenAIModelFactory.cs | 1620 ++ .../AddUploadPartRequest.Serialization.cs | 174 + .../src/Generated/AddUploadPartRequest.cs | 76 + .../AudioOutputParameters.Serialization.cs} | 80 +- .../src/Generated/AudioOutputParameters.cs | 78 + .../AudioResponseData.Serialization.cs | 166 + .../src/Generated/AudioResponseData.cs | 116 + .../src/Generated/AudioTaskLabel.cs | 51 + .../AudioTranscription.Serialization.cs | 240 + .../src/Generated/AudioTranscription.cs | 103 + .../src/Generated/AudioTranscriptionFormat.cs | 63 + ...AudioTranscriptionOptions.Serialization.cs | 313 + .../Generated/AudioTranscriptionOptions.cs | 146 + ...AudioTranscriptionSegment.Serialization.cs | 235 + .../Generated/AudioTranscriptionSegment.cs | 153 + .../AudioTranscriptionTimestampGranularity.cs | 57 + .../AudioTranscriptionWord.Serialization.cs | 158 + .../src/Generated/AudioTranscriptionWord.cs | 87 + .../AudioTranslation.Serialization.cs | 214 + .../src/Generated/AudioTranslation.cs | 98 + .../src/Generated/AudioTranslationFormat.cs | 63 + .../AudioTranslationOptions.Serialization.cs | 264 + .../src/Generated/AudioTranslationOptions.cs | 119 + .../AudioTranslationSegment.Serialization.cs | 235 + .../src/Generated/AudioTranslationSegment.cs | 153 + ...tEnhancementConfiguration.Serialization.cs | 164 + .../AzureChatEnhancementConfiguration.cs | 69 + .../AzureChatEnhancements.Serialization.cs | 149 + .../src/Generated/AzureChatEnhancements.cs | 68 + ...hatExtensionConfiguration.Serialization.cs | 137 + .../AzureChatExtensionConfiguration.cs | 77 + ...ataSourceResponseCitation.Serialization.cs | 208 + ...ChatExtensionDataSourceResponseCitation.cs | 99 + ...rieveDocumentFilterReason.Serialization.cs | 28 + ...atExtensionRetrieveDocumentFilterReason.cs | 18 + ...xtensionRetrievedDocument.Serialization.cs | 268 + .../AzureChatExtensionRetrievedDocument.cs | 123 + .../src/Generated/AzureChatExtensionType.cs | 64 + ...tExtensionsMessageContext.Serialization.cs | 195 + .../AzureChatExtensionsMessageContext.cs | 89 + ...gEnhancementConfiguration.Serialization.cs | 142 + ...reChatGroundingEnhancementConfiguration.cs | 72 + ...REnhancementConfiguration.Serialization.cs | 142 + .../AzureChatOCREnhancementConfiguration.cs | 72 + ...hatExtensionConfiguration.Serialization.cs | 134 + ...AzureCosmosDBChatExtensionConfiguration.cs | 50 + ...DBChatExtensionParameters.Serialization.cs | 302 + .../AzureCosmosDBChatExtensionParameters.cs | 175 + ...smosDBFieldMappingOptions.Serialization.cs | 221 + .../AzureCosmosDBFieldMappingOptions.cs | 99 + ...AzureGroundingEnhancement.Serialization.cs | 152 + .../Generated/AzureGroundingEnhancement.cs | 76 + ...nhancementCoordinatePoint.Serialization.cs | 150 + ...zureGroundingEnhancementCoordinatePoint.cs | 78 + ...eGroundingEnhancementLine.Serialization.cs | 160 + .../AzureGroundingEnhancementLine.cs | 83 + ...undingEnhancementLineSpan.Serialization.cs | 176 + .../AzureGroundingEnhancementLineSpan.cs | 104 + ...hatExtensionConfiguration.Serialization.cs | 134 + .../AzureSearchChatExtensionConfiguration.cs | 50 + ...chChatExtensionParameters.Serialization.cs | 347 + .../AzureSearchChatExtensionParameters.cs | 167 + ...hIndexFieldMappingOptions.Serialization.cs | 261 + .../AzureSearchIndexFieldMappingOptions.cs | 92 + .../src/Generated/AzureSearchQueryType.cs | 60 + .../src/Generated/Batch.Serialization.cs | 429 + .../Azure.AI.OpenAI/src/Generated/Batch.cs | 156 + .../BatchCreateRequest.Serialization.cs | 184 + .../src/Generated/BatchCreateRequest.cs | 94 + .../BatchErrorDatum.Serialization.cs | 182 + .../src/Generated/BatchErrorDatum.cs | 77 + .../Generated/BatchErrorList.Serialization.cs | 167 + .../src/Generated/BatchErrorList.cs | 71 + .../src/Generated/BatchErrorListObject.cs | 48 + .../src/Generated/BatchObject.cs | 48 + .../BatchRequestCounts.Serialization.cs | 179 + .../src/Generated/BatchRequestCounts.cs | 73 + .../src/Generated/BatchStatus.cs | 69 + .../src/Generated/ChatChoice.Serialization.cs | 250 + .../src/Generated/ChatChoice.cs | 120 + ...tChoiceLogProbabilityInfo.Serialization.cs | 194 + .../Generated/ChatChoiceLogProbabilityInfo.cs | 79 + .../src/Generated/ChatCompletionModality.cs | 51 + ...atCompletionStreamOptions.Serialization.cs | 149 + .../Generated/ChatCompletionStreamOptions.cs | 65 + .../ChatCompletions.Serialization.cs | 238 + .../src/Generated/ChatCompletions.cs | 143 + ...mpletionsFunctionToolCall.Serialization.cs | 140 + .../ChatCompletionsFunctionToolCall.cs | 50 + ...onsFunctionToolDefinition.Serialization.cs | 134 + .../ChatCompletionsFunctionToolDefinition.cs | 44 + ...ionToolDefinitionFunction.Serialization.cs | 198 + ...mpletionsFunctionToolDefinitionFunction.cs | 116 + ...ionsFunctionToolSelection.Serialization.cs | 142 + .../ChatCompletionsFunctionToolSelection.cs} | 34 +- ...letionsJsonResponseFormat.Serialization.cs | 126 + .../ChatCompletionsJsonResponseFormat.cs | 29 + ...sJsonSchemaResponseFormat.Serialization.cs | 134 + ...ChatCompletionsJsonSchemaResponseFormat.cs | 47 + ...aResponseFormatJsonSchema.Serialization.cs | 198 + ...tionsJsonSchemaResponseFormatJsonSchema.cs | 116 + ...amedFunctionToolSelection.Serialization.cs | 134 + ...atCompletionsNamedFunctionToolSelection.cs | 44 + ...letionsNamedToolSelection.Serialization.cs | 133 + .../ChatCompletionsNamedToolSelection.cs | 69 + .../ChatCompletionsOptions.Serialization.cs | 752 + .../src/Generated/ChatCompletionsOptions.cs | 482 + ...CompletionsResponseFormat.Serialization.cs | 135 + .../ChatCompletionsResponseFormat.cs | 70 + ...letionsTextResponseFormat.Serialization.cs | 126 + .../ChatCompletionsTextResponseFormat.cs | 32 + .../ChatCompletionsToolCall.Serialization.cs | 135 + .../src/Generated/ChatCompletionsToolCall.cs | 84 + ...CompletionsToolDefinition.Serialization.cs | 133 + .../ChatCompletionsToolDefinition.cs | 69 + .../ChatCompletionsToolSelectionPreset.cs | 60 + ...atMessageAudioContentItem.Serialization.cs | 134 + .../Generated/ChatMessageAudioContentItem.cs | 44 + .../ChatMessageContentItem.Serialization.cs | 136 + .../src/Generated/ChatMessageContentItem.cs | 69 + ...atMessageImageContentItem.Serialization.cs | 134 + .../Generated/ChatMessageImageContentItem.cs | 44 + .../Generated/ChatMessageImageDetailLevel.cs | 60 + .../ChatMessageImageUrl.Serialization.cs | 157 + .../src/Generated/ChatMessageImageUrl.cs} | 52 +- ...MessageRefusalContentItem.Serialization.cs | 134 + .../ChatMessageRefusalContentItem.cs | 44 + ...hatMessageTextContentItem.Serialization.cs | 134 + .../Generated/ChatMessageTextContentItem.cs | 44 + ...atRequestAssistantMessage.Serialization.cs | 234 + .../Generated/ChatRequestAssistantMessage.cs | 117 + ...atRequestDeveloperMessage.Serialization.cs | 152 + .../Generated/ChatRequestDeveloperMessage.cs | 91 + ...hatRequestFunctionMessage.Serialization.cs | 154 + .../Generated/ChatRequestFunctionMessage.cs | 50 + .../ChatRequestMessage.Serialization.cs | 138 + .../src/Generated/ChatRequestMessage.cs | 69 + .../ChatRequestSystemMessage.Serialization.cs | 152 + .../src/Generated/ChatRequestSystemMessage.cs | 91 + .../ChatRequestToolMessage.Serialization.cs | 161 + .../src/Generated/ChatRequestToolMessage.cs | 90 + .../ChatRequestUserMessage.Serialization.cs | 152 + .../src/Generated/ChatRequestUserMessage.cs | 88 + .../ChatResponseMessage.Serialization.cs | 260 + .../src/Generated/ChatResponseMessage.cs | 129 + .../Azure.AI.OpenAI/src/Generated/ChatRole.cs | 63 + ...atTokenLogProbabilityInfo.Serialization.cs | 180 + .../Generated/ChatTokenLogProbabilityInfo.cs | 88 + ...TokenLogProbabilityResult.Serialization.cs | 210 + .../ChatTokenLogProbabilityResult.cs | 94 + .../src/Generated/Choice.Serialization.cs | 211 + .../Azure.AI.OpenAI/src/Generated/Choice.cs | 109 + .../CompleteUploadRequest.Serialization.cs | 163 + .../src/Generated/CompleteUploadRequest.cs | 80 + .../Generated/Completions.Serialization.cs | 226 + .../src/Generated/Completions.cs | 141 + .../src/Generated/CompletionsFinishReason.cs | 63 + ...etionsLogProbabilityModel.Serialization.cs | 253 + .../CompletionsLogProbabilityModel.cs | 97 + .../CompletionsOptions.Serialization.cs | 443 + .../src/Generated/CompletionsOptions.cs | 266 + .../CompletionsUsage.Serialization.cs | 194 + .../src/Generated/CompletionsUsage.cs | 96 + ...geCompletionTokensDetails.Serialization.cs | 194 + ...CompletionsUsageCompletionTokensDetails.cs | 95 + ...sUsagePromptTokensDetails.Serialization.cs | 164 + .../CompletionsUsagePromptTokensDetails.cs | 69 + ...ntFilterBlocklistIdResult.Serialization.cs | 150 + .../ContentFilterBlocklistIdResult.cs | 81 + ...ilterCitedDetectionResult.Serialization.cs | 176 + .../ContentFilterCitedDetectionResult.cs | 86 + ...tFilterCompletionTextSpan.Serialization.cs | 150 + .../ContentFilterCompletionTextSpan.cs | 90 + ...CompletionTextSpanResult.Serialization.cs} | 83 +- .../ContentFilterCompletionTextSpanResult.cs | 88 + ...tentFilterDetailedResults.Serialization.cs | 160 + .../Generated/ContentFilterDetailedResults.cs | 82 + ...tentFilterDetectionResult.Serialization.cs | 150 + .../Generated/ContentFilterDetectionResult.cs | 78 + .../ContentFilterResult.Serialization.cs | 150 + .../src/Generated/ContentFilterResult.cs | 78 + ...terResultDetailsForPrompt.Serialization.cs | 279 + .../ContentFilterResultDetailsForPrompt.cs | 137 + ...entFilterResultsForChoice.Serialization.cs | 295 + .../ContentFilterResultsForChoice.cs | 141 + ...entFilterResultsForPrompt.Serialization.cs | 150 + .../ContentFilterResultsForPrompt.cs | 81 + .../{Models => }/ContentFilterSeverity.cs | 67 +- .../CreateUploadRequest.Serialization.cs | 166 + .../src/Generated/CreateUploadRequest.cs | 118 + .../Generated/CreateUploadRequestPurpose.cs | 57 + ...hatExtensionConfiguration.Serialization.cs | 134 + ...ElasticsearchChatExtensionConfiguration.cs | 50 + ...chChatExtensionParameters.Serialization.cs | 323 + .../ElasticsearchChatExtensionParameters.cs | 159 + ...hIndexFieldMappingOptions.Serialization.cs | 235 + .../ElasticsearchIndexFieldMappingOptions.cs | 87 + .../src/Generated/ElasticsearchQueryType.cs | 51 + .../src/Generated/EmbeddingEncodingFormat.cs | 51 + .../Generated/EmbeddingItem.Serialization.cs} | 90 +- .../src/Generated/EmbeddingItem.cs | 95 + .../src/Generated/EmbeddingItemObject.cs | 48 + .../src/Generated/Embeddings.Serialization.cs | 160 + .../src/Generated/Embeddings.cs | 87 + .../EmbeddingsOptions.Serialization.cs | 222 + .../src/Generated/EmbeddingsOptions.cs | 132 + .../EmbeddingsUsage.Serialization.cs | 150 + .../src/Generated/EmbeddingsUsage.cs | 78 + .../FileDeletionStatus.Serialization.cs | 158 + .../src/Generated/FileDeletionStatus.cs | 85 + .../src/Generated/FileDeletionStatusObject.cs | 48 + .../FileListResponse.Serialization.cs | 160 + .../src/Generated/FileListResponse.cs | 81 + .../src/Generated/FileListResponseObject.cs | 48 + .../src/Generated/FilePurpose.cs | 66 + .../src/Generated/FileState.cs | 75 + .../Generated/FunctionCall.Serialization.cs | 150 + .../src/Generated/FunctionCall.cs | 97 + .../src/Generated/FunctionCallPreset.cs | 60 + .../FunctionDefinition.Serialization.cs | 175 + .../src/Generated/FunctionDefinition.cs | 118 + .../Generated/FunctionName.Serialization.cs | 142 + .../src/Generated/FunctionName.cs | 78 + ...ationContentFilterResults.Serialization.cs | 194 + .../ImageGenerationContentFilterResults.cs | 111 + .../ImageGenerationData.Serialization.cs} | 128 +- .../src/Generated/ImageGenerationData.cs | 104 + .../ImageGenerationOptions.Serialization.cs | 248 + .../src/Generated/ImageGenerationOptions.cs | 137 + ...rationPromptFilterResults.Serialization.cs | 247 + .../ImageGenerationPromptFilterResults.cs | 123 + .../src/Generated/ImageGenerationQuality.cs | 54 + .../ImageGenerationResponseFormat.cs | 51 + .../src/Generated/ImageGenerationStyle.cs | 57 + .../ImageGenerations.Serialization.cs | 160 + .../src/Generated/ImageGenerations.cs | 91 + .../src/Generated/ImageSize.cs | 75 + .../InputAudioContent.Serialization.cs | 150 + .../src/Generated/InputAudioContent.cs | 81 + .../src/Generated/InputAudioFormat.cs | 51 + .../src/Generated/Internal/Argument.cs | 13 +- .../Internal/ChangeTrackingDictionary.cs | 14 +- .../Generated/Internal/ChangeTrackingList.cs | 9 +- .../Internal/ClientPipelineExtensions.cs | 41 - .../Generated/Internal/ClientUriBuilder.cs | 118 - .../src/Generated/Internal/ErrorResult.cs | 24 - .../Internal/ModelSerializationExtensions.cs | 165 +- .../MultipartFormDataRequestContent.cs | 203 + .../src/Generated/Internal/Optional.cs | 15 +- .../PipelineRequestHeadersExtensions.cs | 25 - .../src/Generated/Internal/TypeFormatters.cs | 150 - ...ryContent.cs => Utf8JsonRequestContent.cs} | 12 +- .../Models/AzureFileExpirationAnchor.cs | 59 - ...zureFileExpirationOptions.Serialization.cs | 166 - .../Models/AzureFileExpirationOptions.cs | 45 - .../AzureOpenAIChatError.Serialization.cs | 194 - .../Generated/Models/AzureOpenAIChatError.cs | 51 - ...reOpenAIChatErrorResponse.Serialization.cs | 144 - .../Models/AzureOpenAIChatErrorResponse.cs | 35 - .../AzureOpenAIDalleError.Serialization.cs | 194 - .../Generated/Models/AzureOpenAIDalleError.cs | 51 - ...eOpenAIDalleErrorResponse.Serialization.cs | 144 - .../Models/AzureOpenAIDalleErrorResponse.cs | 35 - ...AzureSearchChatDataSource.Serialization.cs | 139 - .../Models/AzureSearchChatDataSource.cs | 11 - .../Models/ChatCitation.Serialization.cs | 221 - .../src/Generated/Models/ChatCitation.cs | 54 - .../Models/ChatDataSource.Serialization.cs | 157 - .../src/Generated/Models/ChatDataSource.cs | 43 - .../Models/ChatDocumentFilterReason.cs | 62 - .../ChatMessageContext.Serialization.cs | 191 - .../Generated/Models/ChatMessageContext.cs | 46 - .../ChatRetrievedDocument.Serialization.cs | 299 - .../Generated/Models/ChatRetrievedDocument.cs | 73 - ...tentFilterBlocklistResult.Serialization.cs | 179 - .../Models/ContentFilterBlocklistResult.cs | 39 - ...tentFilterDetectionResult.Serialization.cs | 165 - .../Models/ContentFilterDetectionResult.cs | 45 - ...tedMaterialCitationResult.Serialization.cs | 165 - ...ntFilterProtectedMaterialCitationResult.cs | 37 - ...erProtectedMaterialResult.Serialization.cs | 180 - .../ContentFilterProtectedMaterialResult.cs | 46 - ...ntentFilterSeverityResult.Serialization.cs | 165 - .../Models/ContentFilterSeverityResult.cs | 42 - .../ContentFilterTextSpan.Serialization.cs | 165 - .../Generated/Models/ContentFilterTextSpan.cs | 42 - ...ntentFilterTextSpanResult.Serialization.cs | 186 - .../Models/ContentFilterTextSpanResult.cs | 48 - .../CosmosChatDataSource.Serialization.cs | 139 - .../Generated/Models/CosmosChatDataSource.cs | 11 - .../DataSourceAuthentication.Serialization.cs | 163 - .../Models/DataSourceAuthentication.cs | 40 - .../DataSourceFieldMappings.Serialization.cs | 303 - .../Models/DataSourceFieldMappings.cs | 35 - .../Generated/Models/DataSourceQueryType.cs | 74 - .../DataSourceVectorizer.Serialization.cs | 155 - .../Generated/Models/DataSourceVectorizer.cs | 40 - ...asticsearchChatDataSource.Serialization.cs | 139 - .../Models/ElasticsearchChatDataSource.cs | 11 - ...SourceParametersQueryType.Serialization.cs | 31 - ...searchChatDataSourceParametersQueryType.cs | 15 - ...okenAuthenticationOptions.Serialization.cs | 133 - ...aSourceAccessTokenAuthenticationOptions.cs | 28 - ...iKeyAuthenticationOptions.Serialization.cs | 133 - ...atDataSourceApiKeyAuthenticationOptions.cs | 28 - ...ringAuthenticationOptions.Serialization.cs | 133 - ...ceConnectionStringAuthenticationOptions.cs | 28 - ...ntNameVectorizationSource.Serialization.cs | 148 - ...SourceDeploymentNameVectorizationSource.cs | 38 - ...iKeyAuthenticationOptions.Serialization.cs | 133 - ...ourceEncodedApiKeyAuthenticationOptions.cs | 28 - ...dpointVectorizationSource.Serialization.cs | 159 - ...atDataSourceEndpointVectorizationSource.cs | 43 - ...gratedVectorizationSource.Serialization.cs | 118 - ...DataSourceIntegratedVectorizationSource.cs | 20 - ...eyIdAuthenticationOptions.Serialization.cs | 144 - ...aSourceKeyAndKeyIdAuthenticationOptions.cs | 34 - ...odelIdVectorizationSource.Serialization.cs | 133 - ...hatDataSourceModelIdVectorizationSource.cs | 28 - ...tityAuthenticationOptions.Serialization.cs | 118 - ...nedManagedIdentityAuthenticationOptions.cs | 20 - ...tityAuthenticationOptions.Serialization.cs | 133 - ...nedManagedIdentityAuthenticationOptions.cs | 28 - ...wordAuthenticationOptions.Serialization.cs | 144 - ...sernameAndPasswordAuthenticationOptions.cs | 34 - ...ntFilterBlocklistIdResult.Serialization.cs | 155 - ...rnalAzureContentFilterBlocklistIdResult.cs | 41 - ...lterBlocklistResultDetail.Serialization.cs | 155 - ...AzureContentFilterBlocklistResultDetail.cs | 41 - ...ilterResultForChoiceError.Serialization.cs | 155 - ...lAzureContentFilterResultForChoiceError.cs | 41 - ...romptContentFilterResults.Serialization.cs | 270 - ...lterResultForPromptContentFilterResults.cs | 96 - ...BChatDataSourceParameters.Serialization.cs | 325 - ...alAzureCosmosDBChatDataSourceParameters.cs | 91 - ...OpenAIChatErrorInnerError.Serialization.cs | 170 - .../InternalAzureOpenAIChatErrorInnerError.cs | 43 - ...ernalAzureOpenAIChatErrorInnerErrorCode.cs | 44 - ...penAIDalleErrorInnerError.Serialization.cs | 170 - ...InternalAzureOpenAIDalleErrorInnerError.cs | 43 - ...rnalAzureOpenAIDalleErrorInnerErrorCode.cs | 44 - ...hChatDataSourceParameters.Serialization.cs | 361 - ...rnalAzureSearchChatDataSourceParameters.cs | 90 - ...hChatDataSourceParametersIncludeContext.cs | 52 - ...hChatDataSourceParameters.Serialization.cs | 337 - ...alElasticsearchChatDataSourceParameters.cs | 82 - ...BChatDataSourceParameters.Serialization.cs | 349 - ...InternalMongoDBChatDataSourceParameters.cs | 103 - ...eChatDataSourceParameters.Serialization.cs | 313 - ...nternalPineconeChatDataSourceParameters.cs | 85 - ...nknownAzureChatDataSource.Serialization.cs | 105 - .../InternalUnknownAzureChatDataSource.cs | 16 - ...urceAuthenticationOptions.Serialization.cs | 105 - ...zureChatDataSourceAuthenticationOptions.cs | 16 - ...SourceVectorizationSource.Serialization.cs | 105 - ...nAzureChatDataSourceVectorizationSource.cs | 16 - .../MongoDBChatDataSource.Serialization.cs | 139 - .../Generated/Models/MongoDBChatDataSource.cs | 11 - .../PineconeChatDataSource.Serialization.cs | 139 - .../Models/PineconeChatDataSource.cs | 11 - ...equestContentFilterResult.Serialization.cs | 169 - .../Models/RequestContentFilterResult.cs | 34 - ...tImageContentFilterResult.Serialization.cs | 214 - .../Models/RequestImageContentFilterResult.cs | 41 - ...sponseContentFilterResult.Serialization.cs | 300 - .../Models/ResponseContentFilterResult.cs | 85 - ...eImageContentFilterResult.Serialization.cs | 199 - .../ResponseImageContentFilterResult.cs | 64 - .../UserSecurityContext.Serialization.cs | 183 - .../Generated/Models/UserSecurityContext.cs | 32 - ...hatExtensionConfiguration.Serialization.cs | 134 + .../MongoDBChatExtensionConfiguration.cs | 47 + ...DBChatExtensionParameters.Serialization.cs | 327 + .../MongoDBChatExtensionParameters.cs | 219 + ...onParametersFieldsMapping.Serialization.cs | 221 + ...oDBChatExtensionParametersFieldsMapping.cs | 99 + ...okenAuthenticationOptions.Serialization.cs | 134 + ...ourDataAccessTokenAuthenticationOptions.cs | 44 + ...iKeyAuthenticationOptions.Serialization.cs | 134 + .../OnYourDataApiKeyAuthenticationOptions.cs | 44 + ...DataAuthenticationOptions.Serialization.cs | 140 + .../OnYourDataAuthenticationOptions.cs | 69 + .../Generated/OnYourDataAuthenticationType.cs | 69 + ...ringAuthenticationOptions.Serialization.cs | 134 + ...taConnectionStringAuthenticationOptions.cs | 44 + .../Generated/OnYourDataContextProperty.cs | 54 + ...ntNameVectorizationSource.Serialization.cs | 149 + ...urDataDeploymentNameVectorizationSource.cs | 51 + ...iKeyAuthenticationOptions.Serialization.cs | 134 + ...rDataEncodedApiKeyAuthenticationOptions.cs | 44 + ...dpointVectorizationSource.Serialization.cs | 142 + .../OnYourDataEndpointVectorizationSource.cs | 66 + ...gratedVectorizationSource.Serialization.cs | 126 + ...OnYourDataIntegratedVectorizationSource.cs | 29 + ...eyIdAuthenticationOptions.Serialization.cs | 142 + ...ourDataKeyAndKeyIdAuthenticationOptions.cs | 51 + ...odelIdVectorizationSource.Serialization.cs | 134 + .../OnYourDataModelIdVectorizationSource.cs | 47 + ...tityAuthenticationOptions.Serialization.cs | 126 + ...nedManagedIdentityAuthenticationOptions.cs | 29 + ...tityAuthenticationOptions.Serialization.cs | 134 + ...nedManagedIdentityAuthenticationOptions.cs | 44 + ...wordAuthenticationOptions.Serialization.cs | 142 + ...sernameAndPasswordAuthenticationOptions.cs | 51 + ...okenAuthenticationOptions.Serialization.cs | 134 + ...rSearchAccessTokenAuthenticationOptions.cs | 44 + ...iKeyAuthenticationOptions.Serialization.cs | 134 + ...VectorSearchApiKeyAuthenticationOptions.cs | 44 + ...archAuthenticationOptions.Serialization.cs | 134 + ...urDataVectorSearchAuthenticationOptions.cs | 69 + ...nYourDataVectorSearchAuthenticationType.cs | 51 + ...urDataVectorizationSource.Serialization.cs | 136 + .../OnYourDataVectorizationSource.cs | 69 + .../OnYourDataVectorizationSourceType.cs | 67 + .../src/Generated/OpenAIClient.cs | 2859 ++++ .../src/Generated/OpenAIClientOptions.cs | 79 + .../src/Generated/OpenAIFile.Serialization.cs | 217 + .../src/Generated/OpenAIFile.cs} | 62 +- .../src/Generated/OpenAIFileObject.cs | 48 + ...OpenAIPageableListOfBatch.Serialization.cs | 210 + .../Generated/OpenAIPageableListOfBatch.cs | 83 + .../OpenAIPageableListOfBatchObject.cs | 48 + .../src/Generated/OutputAudioFormat.cs | 60 + ...hatExtensionConfiguration.Serialization.cs | 134 + .../PineconeChatExtensionConfiguration.cs | 50 + ...neChatExtensionParameters.Serialization.cs | 293 + .../PineconeChatExtensionParameters.cs | 165 + ...neconeFieldMappingOptions.Serialization.cs | 202 + .../Generated/PineconeFieldMappingOptions.cs | 92 + .../PredictionContent.Serialization.cs | 157 + .../src/Generated/PredictionContent.cs | 136 + .../src/Generated/PredictionContentType.cs | 48 + .../src/Generated/ReasoningEffortValue.cs | 54 + .../SpeechGenerationOptions.Serialization.cs | 197 + .../src/Generated/SpeechGenerationOptions.cs | 93 + .../SpeechGenerationResponseFormat.cs | 63 + .../src/Generated/SpeechVoice.cs | 63 + ...hatExtensionConfiguration.Serialization.cs | 126 + .../UnknownAzureChatExtensionConfiguration.cs | 31 + ...letionsNamedToolSelection.Serialization.cs | 126 + ...nknownChatCompletionsNamedToolSelection.cs | 28 + ...CompletionsResponseFormat.Serialization.cs | 126 + .../UnknownChatCompletionsResponseFormat.cs | 28 + ...nChatCompletionsToolCall.Serialization.cs} | 54 +- .../UnknownChatCompletionsToolCall.cs | 29 + ...CompletionsToolDefinition.Serialization.cs | 126 + .../UnknownChatCompletionsToolDefinition.cs | 28 + ...ownChatMessageContentItem.Serialization.cs | 126 + .../UnknownChatMessageContentItem.cs | 28 + ...UnknownChatRequestMessage.Serialization.cs | 126 + .../Generated/UnknownChatRequestMessage.cs | 28 + ...DataAuthenticationOptions.Serialization.cs | 126 + .../UnknownOnYourDataAuthenticationOptions.cs | 28 + ...archAuthenticationOptions.Serialization.cs | 126 + ...urDataVectorSearchAuthenticationOptions.cs | 28 + ...urDataVectorizationSource.Serialization.cs | 126 + .../UnknownOnYourDataVectorizationSource.cs | 28 + .../src/Generated/Upload.Serialization.cs | 238 + .../Azure.AI.OpenAI/src/Generated/Upload.cs | 120 + .../UploadFileRequest.Serialization.cs} | 85 +- .../src/Generated/UploadFileRequest.cs | 86 + .../src/Generated/UploadObject.cs | 48 + .../src/Generated/UploadPart.Serialization.cs | 183 + .../src/Generated/UploadPart.cs | 97 + .../src/Generated/UploadPartObject.cs | 48 + .../src/Generated/UploadPurpose.cs | 66 + .../src/Generated/UploadStatus.cs | 57 + .../UserSecurityContext.Serialization.cs | 178 + .../src/Generated/UserSecurityContext.cs | 71 + sdk/openai/Azure.AI.OpenAI/tsp-location.yaml | 4 + .../tsp-location.yaml | 4 + ...Communication.ProgrammableConnectivity.sln | 56 + .../CHANGELOG.md | 11 + .../Directory.Build.props | 6 + .../README.md | 107 + ...ication.ProgrammableConnectivity.net8.0.cs | 255 + ...ProgrammableConnectivity.netstandard2.0.cs | 255 + ...munication.ProgrammableConnectivity.csproj | 19 + ...ableConnectivityClientBuilderExtensions.cs | 35 + ...ionProgrammableConnectivityModelFactory.cs | 87 + .../src/Generated/DeviceLocation.cs | 199 + ...cationVerificationContent.Serialization.cs | 180 + .../DeviceLocationVerificationContent.cs | 100 + ...ocationVerificationResult.Serialization.cs | 142 + .../DeviceLocationVerificationResult.cs | 72 + .../src/Generated/DeviceNetwork.cs | 199 + .../src/Generated/Docs/DeviceLocation.xml | 121 + .../src/Generated/Docs/DeviceNetwork.xml | 67 + .../src/Generated/Docs/NumberVerification.xml | 145 + .../src/Generated/Docs/SimSwap.xml | 157 + .../src/Generated/Internal/Argument.cs | 129 + .../Internal/ChangeTrackingDictionary.cs | 167 + .../Generated/Internal/ChangeTrackingList.cs | 153 + .../Internal/ModelSerializationExtensions.cs | 399 + .../src/Generated/Internal/Optional.cs | 51 + .../Internal/Utf8JsonRequestContent.cs | 55 + .../Generated/Ipv4Address.Serialization.cs | 150 + .../src/Generated/Ipv4Address.cs | 81 + .../Generated/Ipv6Address.Serialization.cs | 150 + .../src/Generated/Ipv6Address.cs | 81 + .../Generated/LocationDevice.Serialization.cs | 186 + .../src/Generated/LocationDevice.cs | 77 + .../NetworkIdentifier.Serialization.cs | 150 + .../src/Generated/NetworkIdentifier.cs | 91 + .../NetworkRetrievalResult.Serialization.cs | 142 + .../src/Generated/NetworkRetrievalResult.cs | 75 + .../src/Generated/NumberVerification.cs | 347 + .../NumberVerificationResult.Serialization.cs | 142 + .../src/Generated/NumberVerificationResult.cs | 72 + ...rificationWithCodeContent.Serialization.cs | 142 + .../NumberVerificationWithCodeContent.cs | 75 + ...icationWithoutCodeContent.Serialization.cs | 172 + .../NumberVerificationWithoutCodeContent.cs | 90 + .../ProgrammableConnectivityClient.cs | 99 + .../ProgrammableConnectivityClientOptions.cs | 37 + .../src/Generated/SimSwap.cs | 332 + .../SimSwapRetrievalContent.Serialization.cs | 153 + .../src/Generated/SimSwapRetrievalContent.cs | 79 + .../SimSwapRetrievalResult.Serialization.cs | 149 + .../src/Generated/SimSwapRetrievalResult.cs | 65 + ...imSwapVerificationContent.Serialization.cs | 168 + .../Generated/SimSwapVerificationContent.cs | 83 + ...SimSwapVerificationResult.Serialization.cs | 142 + .../Generated/SimSwapVerificationResult.cs | 72 + .../src/Properties/AssemblyInfo.cs | 11 + ...tion.ProgrammableConnectivity.Tests.csproj | 20 + .../Samples/Samples_DeviceLocation.cs | 135 + .../Samples/Samples_DeviceNetwork.cs | 81 + .../Samples/Samples_NumberVerification.cs | 159 + .../Generated/Samples/Samples_SimSwap.cs | 171 + .../tsp-location.yaml | 4 + sdk/programmableconnectivity/ci.yml | 35 + .../src/autorest.md | 5 +- .../src/autorest.md | 6 +- .../src/autorest.md | 6 +- .../src/Generated/Entity.cs | 4 +- .../tsp-location.yaml | 6 +- .../src/autorest.md | 5 +- .../src/autorest.md | 5 +- .../src/autorest.md | 5 +- .../tsp-location.yaml | 6 +- sdk/storage/ci.yml | 2 + .../Azure.AI.Translation.Document.net8.0.cs | 25 +- ....AI.Translation.Document.netstandard2.0.cs | 25 +- .../Generated/BatchOptions.Serialization.cs | 149 + .../src/Generated/BatchOptions.cs | 65 + .../DocumentStatusResult.Serialization.cs | 32 + .../src/Generated/DocumentStatusResult.cs | 10 +- .../DocumentTranslationClientOptions.cs | 4 +- .../SingleDocumentTranslationClient.cs | 30 +- .../TranslationBatch.Serialization.cs | 17 +- .../src/Generated/TranslationBatch.cs | 6 +- .../TranslationStatusSummary.Serialization.cs | 32 + .../src/Generated/TranslationStatusSummary.cs | 10 +- .../tsp-location.yaml | 3 +- .../api/Azure.AI.Translation.Text.net8.0.cs | 48 +- ...zure.AI.Translation.Text.netstandard2.0.cs | 48 +- .../AITranslationTextModelFactory.cs | 84 +- .../BackTranslation.Serialization.cs | 2 +- .../src/Generated/BackTranslation.cs | 14 +- .../BreakSentenceItem.Serialization.cs | 2 +- .../src/Generated/BreakSentenceItem.cs | 18 +- .../DetectedLanguage.Serialization.cs | 2 +- .../src/Generated/DetectedLanguage.cs | 14 +- .../Generated/LanguageScript.Serialization.cs | 2 +- .../src/Generated/LanguageScript.cs | 14 +- .../SentenceBoundaries.Serialization.cs | 4 +- .../src/Generated/SentenceBoundaries.cs | 30 +- .../SourceDictionaryLanguage.Serialization.cs | 2 +- .../src/Generated/SourceDictionaryLanguage.cs | 14 +- .../TargetDictionaryLanguage.Serialization.cs | 2 +- .../src/Generated/TargetDictionaryLanguage.cs | 14 +- .../src/Generated/TextTranslationClient.cs | 40 +- .../TranslatedTextAlignment.Serialization.cs | 2 +- .../src/Generated/TranslatedTextAlignment.cs | 18 +- .../TranslationLanguage.Serialization.cs | 2 +- .../src/Generated/TranslationLanguage.cs | 14 +- .../TranslationText.Serialization.cs | 6 +- .../src/Generated/TranslationText.cs | 24 +- .../TransliterableScript.Serialization.cs | 2 +- .../src/Generated/TransliterableScript.cs | 22 +- .../tsp-location.yaml | 3 +- 1092 files changed, 131153 insertions(+), 18823 deletions(-) create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/Microsoft.VoiceServices.Provisioning.sln create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Accounts.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/Accounts.xml create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/TeamsRequestsForInformation.xml create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/VoiceServicesClient.xml create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Argument.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingDictionary.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingList.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ModelSerializationExtensions.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Optional.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Utf8JsonRequestContent.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningClientBuilderExtensions.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningModelFactory.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ServiceProvisioningStatus.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsConsentStatus.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainProvisioningStatus.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsRequestsForInformation.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TelephoneNumberAssignmentStatus.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ValidationStatus.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClient.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClientOptions.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.Serialization.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Microsoft.VoiceServices.Provisioning.csproj create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Properties/AssemblyInfo.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_Accounts.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_TeamsRequestsForInformation.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_VoiceServicesClient.cs create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Microsoft.VoiceServices.Provisioning.Tests.csproj create mode 100644 sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tsp-location.yaml create mode 100644 sdk/apicenter/azure.ApiCenter/Configuration.json create mode 100644 sdk/apicenter/azure.ApiCenter/tsp-location.yaml create mode 100644 sdk/apicenter/azure.ApiCenter/tspCodeModel.json create mode 100644 sdk/appconfiguration/Azure.Data.AppConfiguration/Configuration.json delete mode 100644 sdk/appconfiguration/Azure.Data.AppConfiguration/src/autorest.md create mode 100644 sdk/appconfiguration/Azure.Data.AppConfiguration/tsp-location.yaml create mode 100644 sdk/appconfiguration/Azure.Data.AppConfiguration/tspCodeModel.json create mode 100644 sdk/applicationinsights/LiveMetrics/LiveMetrics.sln create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/AggregationType.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationErrorType.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Docs/LiveMetricsClient.xml create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/DocumentType.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Event.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Event.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Exception.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Exception.cs rename sdk/{openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.Serialization.cs => applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.Serialization.cs} (63%) create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Argument.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Optional.cs rename sdk/{openai/Azure.AI.OpenAI/src/Generated/Internal/BinaryContentHelper.cs => applicationinsights/LiveMetrics/src/Generated/Internal/RequestContentHelper.cs} (62%) create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClient.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientBuilderExtensions.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientOptions.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsModelFactory.cs rename sdk/{openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.Serialization.cs => applicationinsights/LiveMetrics/src/Generated/MetricPoint.Serialization.cs} (64%) create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/MetricPoint.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/PredicateType.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Request.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Request.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/TelemetryType.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Trace.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/Trace.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.Serialization.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.cs create mode 100644 sdk/applicationinsights/LiveMetrics/src/LiveMetrics.csproj create mode 100644 sdk/applicationinsights/LiveMetrics/src/Properties/AssemblyInfo.cs create mode 100644 sdk/applicationinsights/LiveMetrics/tests/Generated/Samples/Samples_LiveMetricsClient.cs create mode 100644 sdk/applicationinsights/LiveMetrics/tests/LiveMetrics.Tests.csproj create mode 100644 sdk/applicationinsights/LiveMetrics/tsp-location.yaml create mode 100644 sdk/contosowidgetmanager/Azure.Template.Contoso/tsp-location.yaml delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionStatus.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.Serialization.cs rename sdk/face/Azure.AI.Vision.Face/src/Generated/{LivenessOutputsTarget.cs => LivenessColorDecisionTarget.cs} (51%) create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.Serialization.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.Serialization.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.Serialization.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.Serialization.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.Serialization.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.cs delete mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.Serialization.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.cs rename sdk/face/Azure.AI.Vision.Face/src/Generated/{LivenessWithVerifyImage.Serialization.cs => LivenessWithVerifyReference.Serialization.cs} (65%) rename sdk/face/Azure.AI.Vision.Face/src/Generated/{LivenessWithVerifyImage.cs => LivenessWithVerifyReference.cs} (73%) rename sdk/face/Azure.AI.Vision.Face/src/Generated/{LivenessSessionAuditEntry.Serialization.cs => LivenessWithVerifyResult.Serialization.cs} (55%) create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.Serialization.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.Serialization.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.cs create mode 100644 sdk/face/Azure.AI.Vision.Face/src/Generated/OperationState.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/Microsoft.App.DynamicSessions.sln create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeExecution.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeInputType.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/CodeExecution.xml create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/SessionResourceFiles.xml create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClient.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClientOptions.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.Serialization.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ExecutionType.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Argument.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingDictionary.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingList.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ModelSerializationExtensions.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/MultipartFormDataRequestContent.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Optional.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Utf8JsonRequestContent.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsClientBuilderExtensions.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsModelFactory.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/OperationState.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.Serialization.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.Serialization.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.Serialization.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.Serialization.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFiles.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.Serialization.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Microsoft.App.DynamicSessions.csproj create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Properties/AssemblyInfo.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_CodeExecution.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_SessionResourceFiles.cs create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Microsoft.App.DynamicSessions.Tests.csproj create mode 100644 sdk/microsoft.app/Microsoft.App.DynamicSessions/tsp-location.yaml create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ApiResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantStreamEvent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatMode.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiToolChoiceOptionMode.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.Serialization.cs => openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.Serialization.cs} (61%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoiceType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{ThreadInitializationMessage.Serialization.cs => CreateFileSearchToolResourceVectorStoreOptions.Serialization.cs} (62%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/DoneEvent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ErrorEvent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItemType.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{RunStepRetrievalToolCall.Serialization.cs => FileSearchToolDefinition.Serialization.cs} (60%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileState.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/IncompleteRunDetails.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatusObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.Serialization.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{MessageFile.cs => MessageDeltaChunk.cs} (56%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunkObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetailsReason.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStreamEvent.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfAssistantFileObject.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{InternalOpenAIPageableListOfMessageFile.Serialization.cs => OpenAIPageableListOfVectorStore.Serialization.cs} (66%) rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{InternalOpenAIPageableListOfAssistantFile.cs => OpenAIPageableListOfVectorStore.cs} (78%) rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{InternalOpenAIPageableListOfAssistantFile.Serialization.cs => OpenAIPageableListOfVectorStoreFile.Serialization.cs} (65%) rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{InternalOpenAIPageableListOfMessageFile.cs => OpenAIPageableListOfVectorStoreFile.cs} (78%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFileObject.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{OpenAIPageableListOfMessageFileObject.cs => OpenAIPageableListOfVectorStoreObject.cs} (55%) delete mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunIncludes.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunkObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepStreamEvent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStreamEvent.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{CreateMessageRequest.Serialization.cs => ThreadMessageOptions.Serialization.cs} (70%) rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{ThreadInitializationMessage.cs => ThreadMessageOptions.cs} (53%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadStreamEvent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.Serialization.cs => openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.Serialization.cs} (58%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationStrategy.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{UpdateThreadRequest.Serialization.cs => UpdateAssistantThreadOptions.Serialization.cs} (62%) rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{CreateMessageRequest.cs => UpdateAssistantThreadOptions.cs} (53%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequestType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponseType.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{InternalAssistantFileDeletionStatus.Serialization.cs => VectorStoreDeletionStatus.Serialization.cs} (64%) rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{InternalAssistantFileDeletionStatus.cs => VectorStoreDeletionStatus.cs} (71%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatusObject.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.Serialization.cs => openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.Serialization.cs} (65%) create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicyAnchor.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatusObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileErrorCode.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatusFilter.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.Serialization.cs rename sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/{UpdateThreadRequest.cs => VectorStoreUpdateOptions.cs} (69%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIClientBuilderExtensions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIModelFactory.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.Serialization.cs => openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.Serialization.cs} (59%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTaskLabel.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionTimestampGranularity.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchQueryType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorListObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/BatchStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionModality.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.Serialization.cs rename sdk/openai/{Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.cs => Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.cs} (65%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolSelectionPreset.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageDetailLevel.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.Serialization.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.cs => openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.cs} (51%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRole.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsFinishReason.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.Serialization.cs => openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.Serialization.cs} (60%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.cs rename sdk/openai/Azure.AI.OpenAI/src/Generated/{Models => }/ContentFilterSeverity.cs (55%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequestPurpose.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchQueryType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingEncodingFormat.cs rename sdk/openai/{Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.Serialization.cs => Azure.AI.OpenAI/src/Generated/EmbeddingItem.Serialization.cs} (63%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItemObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatusObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponseObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FilePurpose.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FileState.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCallPreset.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.Serialization.cs => openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.Serialization.cs} (55%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationQuality.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationStyle.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ImageSize.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioFormat.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientPipelineExtensions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientUriBuilder.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ErrorResult.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataRequestContent.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/PipelineRequestHeadersExtensions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/TypeFormatters.cs rename sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/{Utf8JsonBinaryContent.cs => Utf8JsonRequestContent.cs} (82%) delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationAnchor.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDocumentFilterReason.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceQueryType.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerErrorCode.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerErrorCode.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParametersIncludeContext.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.Serialization.cs delete mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataContextProperty.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSourceType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClient.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClientOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.Serialization.cs rename sdk/openai/{Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.cs => Azure.AI.OpenAI/src/Generated/OpenAIFile.cs} (51%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFileObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatchObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/OutputAudioFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContentType.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/ReasoningEffortValue.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationResponseFormat.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechVoice.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.cs rename sdk/openai/{Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.Serialization.cs => Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.Serialization.cs} (62%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.cs rename sdk/{face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.Serialization.cs => openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.Serialization.cs} (56%) create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UploadObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPartObject.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPurpose.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UploadStatus.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.Serialization.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.cs create mode 100644 sdk/openai/Azure.AI.OpenAI/tsp-location.yaml create mode 100644 sdk/playwrighttesting/Azure.Developer.MicrosoftPlaywrightTesting/tsp-location.yaml create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Azure.Communication.ProgrammableConnectivity.sln create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/CHANGELOG.md create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Directory.Build.props create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/README.md create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.net8.0.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.netstandard2.0.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Azure.Communication.ProgrammableConnectivity.csproj create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityClientBuilderExtensions.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityModelFactory.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocation.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceNetwork.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceLocation.xml create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceNetwork.xml create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/NumberVerification.xml create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/SimSwap.xml create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Argument.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingDictionary.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingList.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ModelSerializationExtensions.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Optional.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Utf8JsonRequestContent.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerification.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClient.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClientOptions.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwap.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.Serialization.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Properties/AssemblyInfo.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Azure.Communication.ProgrammableConnectivity.Tests.csproj create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceLocation.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceNetwork.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_NumberVerification.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_SimSwap.cs create mode 100644 sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tsp-location.yaml create mode 100644 sdk/programmableconnectivity/ci.yml create mode 100644 sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.Serialization.cs create mode 100644 sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.cs diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/Microsoft.VoiceServices.Provisioning.sln b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/Microsoft.VoiceServices.Provisioning.sln new file mode 100644 index 000000000000..ea653dd6b539 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/Microsoft.VoiceServices.Provisioning.sln @@ -0,0 +1,50 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.VoiceServices.Provisioning", "src\Microsoft.VoiceServices.Provisioning.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.VoiceServices.Provisioning.Tests", "tests\Microsoft.VoiceServices.Provisioning.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.Serialization.cs new file mode 100644 index 000000000000..6695c54b9931 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.Serialization.cs @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class AccountResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AccountResource)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ServiceProvisioningStatus)) + { + writer.WritePropertyName("serviceProvisioningStatus"u8); + writer.WriteStringValue(ServiceProvisioningStatus.Value.ToString()); + } + if (options.Format != "W" && Optional.IsCollectionDefined(ServiceProvisioningErrors)) + { + writer.WritePropertyName("serviceProvisioningErrors"u8); + writer.WriteStartArray(); + foreach (var item in ServiceProvisioningErrors) + { + JsonSerializer.Serialize(writer, item); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Optional.IsDefined(CorrelationId)) + { + writer.WritePropertyName("correlationId"u8); + writer.WriteStringValue(CorrelationId); + } + if (Optional.IsDefined(ServiceDetails)) + { + writer.WritePropertyName("serviceDetails"u8); + writer.WriteObjectValue(ServiceDetails, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AccountResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AccountResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAccountResource(document.RootElement, options); + } + + internal static AccountResource DeserializeAccountResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ServiceProvisioningStatus? serviceProvisioningStatus = default; + IReadOnlyList serviceProvisioningErrors = default; + string name = default; + string correlationId = default; + AccountServiceDetails serviceDetails = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("serviceProvisioningStatus"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + serviceProvisioningStatus = new ServiceProvisioningStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("serviceProvisioningErrors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(JsonSerializer.Deserialize(item.GetRawText())); + } + serviceProvisioningErrors = array; + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("correlationId"u8)) + { + correlationId = property.Value.GetString(); + continue; + } + if (property.NameEquals("serviceDetails"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + serviceDetails = AccountServiceDetails.DeserializeAccountServiceDetails(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AccountResource( + serviceProvisioningStatus, + serviceProvisioningErrors ?? new ChangeTrackingList(), + name, + correlationId, + serviceDetails, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AccountResource)} does not support writing '{options.Format}' format."); + } + } + + AccountResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAccountResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AccountResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AccountResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAccountResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.cs new file mode 100644 index 000000000000..dddd960e8051 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountResource.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// An account represents a group of numbers, typically associated with an enterprise. + public partial class AccountResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Name of the account. + /// is null. + public AccountResource(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + ServiceProvisioningErrors = new ChangeTrackingList(); + Name = name; + } + + /// Initializes a new instance of . + /// The status of the provisioning action associated with this resource. + /// Any errors pertaining to the provisioning of this resource. + /// Name of the account. + /// A user defined identifier used for correlating with external systems. + /// The details of the account. + /// Keeps track of any properties unknown to the library. + internal AccountResource(ServiceProvisioningStatus? serviceProvisioningStatus, IReadOnlyList serviceProvisioningErrors, string name, string correlationId, AccountServiceDetails serviceDetails, IDictionary serializedAdditionalRawData) + { + ServiceProvisioningStatus = serviceProvisioningStatus; + ServiceProvisioningErrors = serviceProvisioningErrors; + Name = name; + CorrelationId = correlationId; + ServiceDetails = serviceDetails; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AccountResource() + { + } + + /// The status of the provisioning action associated with this resource. + public ServiceProvisioningStatus? ServiceProvisioningStatus { get; } + /// Any errors pertaining to the provisioning of this resource. + public IReadOnlyList ServiceProvisioningErrors { get; } + /// Name of the account. + public string Name { get; set; } + /// A user defined identifier used for correlating with external systems. + public string CorrelationId { get; set; } + /// The details of the account. + public AccountServiceDetails ServiceDetails { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.Serialization.cs new file mode 100644 index 000000000000..c12df5c60acf --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.Serialization.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class AccountServiceDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AccountServiceDetails)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(TeamsTenantId)) + { + writer.WritePropertyName("teamsTenantId"u8); + writer.WriteStringValue(TeamsTenantId); + } + if (Optional.IsDefined(TeamsOperatorConnect)) + { + writer.WritePropertyName("teamsOperatorConnect"u8); + writer.WriteObjectValue(TeamsOperatorConnect, options); + } + if (Optional.IsDefined(TeamsDirectRouting)) + { + writer.WritePropertyName("teamsDirectRouting"u8); + writer.WriteObjectValue(TeamsDirectRouting, options); + } + if (Optional.IsDefined(TeamsPhoneMobile)) + { + writer.WritePropertyName("teamsPhoneMobile"u8); + writer.WriteObjectValue(TeamsPhoneMobile, options); + } + if (Optional.IsDefined(ZoomPhoneCloudPeering)) + { + writer.WritePropertyName("zoomPhoneCloudPeering"u8); + writer.WriteObjectValue(ZoomPhoneCloudPeering, options); + } + if (Optional.IsDefined(AzureOperatorCallProtection)) + { + writer.WritePropertyName("azureOperatorCallProtection"u8); + writer.WriteObjectValue(AzureOperatorCallProtection, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AccountServiceDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AccountServiceDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAccountServiceDetails(document.RootElement, options); + } + + internal static AccountServiceDetails DeserializeAccountServiceDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string teamsTenantId = default; + TeamsOperatorConnectAccountDetails teamsOperatorConnect = default; + TeamsDirectRoutingAccountDetails teamsDirectRouting = default; + TeamsPhoneMobileAccountDetails teamsPhoneMobile = default; + ZoomPhoneCloudPeeringAccountDetails zoomPhoneCloudPeering = default; + AzureOperatorCallProtectionAccountDetails azureOperatorCallProtection = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("teamsTenantId"u8)) + { + teamsTenantId = property.Value.GetString(); + continue; + } + if (property.NameEquals("teamsOperatorConnect"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + teamsOperatorConnect = TeamsOperatorConnectAccountDetails.DeserializeTeamsOperatorConnectAccountDetails(property.Value, options); + continue; + } + if (property.NameEquals("teamsDirectRouting"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + teamsDirectRouting = TeamsDirectRoutingAccountDetails.DeserializeTeamsDirectRoutingAccountDetails(property.Value, options); + continue; + } + if (property.NameEquals("teamsPhoneMobile"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + teamsPhoneMobile = TeamsPhoneMobileAccountDetails.DeserializeTeamsPhoneMobileAccountDetails(property.Value, options); + continue; + } + if (property.NameEquals("zoomPhoneCloudPeering"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + zoomPhoneCloudPeering = ZoomPhoneCloudPeeringAccountDetails.DeserializeZoomPhoneCloudPeeringAccountDetails(property.Value, options); + continue; + } + if (property.NameEquals("azureOperatorCallProtection"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + azureOperatorCallProtection = AzureOperatorCallProtectionAccountDetails.DeserializeAzureOperatorCallProtectionAccountDetails(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AccountServiceDetails( + teamsTenantId, + teamsOperatorConnect, + teamsDirectRouting, + teamsPhoneMobile, + zoomPhoneCloudPeering, + azureOperatorCallProtection, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AccountServiceDetails)} does not support writing '{options.Format}' format."); + } + } + + AccountServiceDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAccountServiceDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AccountServiceDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AccountServiceDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAccountServiceDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.cs new file mode 100644 index 000000000000..bb7b248c3374 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AccountServiceDetails.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Details of the backend services associated with this Account. + public partial class AccountServiceDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public AccountServiceDetails() + { + } + + /// Initializes a new instance of . + /// The Microsoft Teams Tenant ID of the Account. This can only be updated if no Operator Connect or Teams Phone Mobile numbers are configured in this account. + /// Details for the Teams Operator Connect service on this Account. + /// Details for the Teams Direct Routing service on this Account. + /// Details for the Teams Phone Mobile service on this Account. + /// Details for the Zoom Phone Cloud Peering service on this Account. + /// Details for the Azure Operator Call Protection service on this Account. + /// Keeps track of any properties unknown to the library. + internal AccountServiceDetails(string teamsTenantId, TeamsOperatorConnectAccountDetails teamsOperatorConnect, TeamsDirectRoutingAccountDetails teamsDirectRouting, TeamsPhoneMobileAccountDetails teamsPhoneMobile, ZoomPhoneCloudPeeringAccountDetails zoomPhoneCloudPeering, AzureOperatorCallProtectionAccountDetails azureOperatorCallProtection, IDictionary serializedAdditionalRawData) + { + TeamsTenantId = teamsTenantId; + TeamsOperatorConnect = teamsOperatorConnect; + TeamsDirectRouting = teamsDirectRouting; + TeamsPhoneMobile = teamsPhoneMobile; + ZoomPhoneCloudPeering = zoomPhoneCloudPeering; + AzureOperatorCallProtection = azureOperatorCallProtection; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The Microsoft Teams Tenant ID of the Account. This can only be updated if no Operator Connect or Teams Phone Mobile numbers are configured in this account. + public string TeamsTenantId { get; set; } + /// Details for the Teams Operator Connect service on this Account. + public TeamsOperatorConnectAccountDetails TeamsOperatorConnect { get; set; } + /// Details for the Teams Direct Routing service on this Account. + public TeamsDirectRoutingAccountDetails TeamsDirectRouting { get; set; } + /// Details for the Teams Phone Mobile service on this Account. + public TeamsPhoneMobileAccountDetails TeamsPhoneMobile { get; set; } + /// Details for the Zoom Phone Cloud Peering service on this Account. + public ZoomPhoneCloudPeeringAccountDetails ZoomPhoneCloudPeering { get; set; } + /// Details for the Azure Operator Call Protection service on this Account. + public AzureOperatorCallProtectionAccountDetails AzureOperatorCallProtection { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Accounts.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Accounts.cs new file mode 100644 index 000000000000..d13e48e1a464 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Accounts.cs @@ -0,0 +1,2036 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Microsoft.VoiceServices.Provisioning +{ + // Data plane generated sub-client. + /// The Accounts sub-client. + public partial class Accounts + { + private static readonly string[] AuthorizationScopes = new string[] { "https://func-voiceservice-rp-prod-eastuseuap.azurewebsites.net/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of Accounts for mocking. + protected Accounts() + { + } + + /// Initializes a new instance of Accounts. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// Service host. + /// The API version to use for this operation. + internal Accounts(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get Account. + /// Name of the account. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get details of a specific Account using its Name. An Account represents an Enterprise or collection of users. + /// + public virtual async Task> GetAccountResourceAsync(string accountName, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAccountResourceAsync(accountName, requestConditions, context).ConfigureAwait(false); + return Response.FromValue(AccountResource.FromResponse(response), response); + } + + /// Get Account. + /// Name of the account. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get details of a specific Account using its Name. An Account represents an Enterprise or collection of users. + /// + public virtual Response GetAccountResource(string accountName, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAccountResource(accountName, requestConditions, context); + return Response.FromValue(AccountResource.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get Account. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetAccountResourceAsync(string accountName, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetAccountResource"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAccountResourceRequest(accountName, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get Account. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetAccountResource(string accountName, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetAccountResource"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAccountResourceRequest(accountName, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Create or Replace Account. + /// Name of the account. + /// The resource instance. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Create or replace the details of an Account. + /// + public virtual async Task> CreateOrReplaceAsync(string accountName, AccountResource resource, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(resource, nameof(resource)); + + using RequestContent content = resource.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateOrReplaceAsync(accountName, content, requestConditions, context).ConfigureAwait(false); + return Response.FromValue(AccountResource.FromResponse(response), response); + } + + /// Create or Replace Account. + /// Name of the account. + /// The resource instance. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Create or replace the details of an Account. + /// + public virtual Response CreateOrReplace(string accountName, AccountResource resource, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(resource, nameof(resource)); + + using RequestContent content = resource.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateOrReplace(accountName, content, requestConditions, context); + return Response.FromValue(AccountResource.FromResponse(response), response); + } + + /// + /// [Protocol Method] Create or Replace Account. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateOrReplaceAsync(string accountName, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.CreateOrReplace"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrReplaceRequest(accountName, content, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create or Replace Account. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CreateOrReplace(string accountName, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.CreateOrReplace"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrReplaceRequest(accountName, content, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete Account. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Name of the account. + /// Whether to delete the child Number resources of the Account, defaults to false. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteAsync(string accountName, bool? deleteNumbers = null, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.Delete"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteRequest(accountName, deleteNumbers, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete Account. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Name of the account. + /// Whether to delete the child Number resources of the Account, defaults to false. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Delete(string accountName, bool? deleteNumbers = null, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.Delete"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteRequest(accountName, deleteNumbers, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Create or update Numbers. + /// Name of the account. + /// Batch of numbers to create or replace. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Create or update up to 100 Numbers on the specified account. + /// + public virtual async Task> CreateOrUpdateNumbersAsync(string accountName, BatchNumbers body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateOrUpdateNumbersAsync(accountName, content, context).ConfigureAwait(false); + return Response.FromValue(BatchNumbers.FromResponse(response), response); + } + + /// Create or update Numbers. + /// Name of the account. + /// Batch of numbers to create or replace. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Create or update up to 100 Numbers on the specified account. + /// + public virtual Response CreateOrUpdateNumbers(string accountName, BatchNumbers body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateOrUpdateNumbers(accountName, content, context); + return Response.FromValue(BatchNumbers.FromResponse(response), response); + } + + /// + /// [Protocol Method] Create or update Numbers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateOrUpdateNumbersAsync(string accountName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.CreateOrUpdateNumbers"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateNumbersRequest(accountName, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create or update Numbers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CreateOrUpdateNumbers(string accountName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.CreateOrUpdateNumbers"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateNumbersRequest(accountName, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Delete Numbers. + /// Name of the account. + /// Batch numbers to delete. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Delete up to 100 Numbers on the specified account. + /// + public virtual async Task DeleteNumbersAsync(string accountName, BatchNumbersDelete body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await DeleteNumbersAsync(accountName, content, context).ConfigureAwait(false); + return response; + } + + /// Delete Numbers. + /// Name of the account. + /// Batch numbers to delete. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Delete up to 100 Numbers on the specified account. + /// + public virtual Response DeleteNumbers(string accountName, BatchNumbersDelete body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = DeleteNumbers(accountName, content, context); + return response; + } + + /// + /// [Protocol Method] Delete Numbers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteNumbersAsync(string accountName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.DeleteNumbers"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteNumbersRequest(accountName, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete Numbers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteNumbers(string accountName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.DeleteNumbers"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteNumbersRequest(accountName, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get Number. + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Get details of a specific Number using its telephone number. + /// + public virtual async Task> GetNumberAsync(string accountName, string telephoneNumber, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetNumberAsync(accountName, telephoneNumber, requestConditions, context).ConfigureAwait(false); + return Response.FromValue(NumberResource.FromResponse(response), response); + } + + /// Get Number. + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Get details of a specific Number using its telephone number. + /// + public virtual Response GetNumber(string accountName, string telephoneNumber, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetNumber(accountName, telephoneNumber, requestConditions, context); + return Response.FromValue(NumberResource.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get Number. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetNumberAsync(string accountName, string telephoneNumber, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetNumber"); + scope.Start(); + try + { + using HttpMessage message = CreateGetNumberRequest(accountName, telephoneNumber, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get Number. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetNumber(string accountName, string telephoneNumber, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetNumber"); + scope.Start(); + try + { + using HttpMessage message = CreateGetNumberRequest(accountName, telephoneNumber, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Create or replace Number. + /// Name of the account. + /// Telephone number in E.164 format. + /// The resource instance. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + /// Create or replace the details of a Number. + /// + public virtual async Task> CreateOrReplaceNumberAsync(string accountName, string telephoneNumber, NumberResource resource, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + Argument.AssertNotNull(resource, nameof(resource)); + + using RequestContent content = resource.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateOrReplaceNumberAsync(accountName, telephoneNumber, content, requestConditions, context).ConfigureAwait(false); + return Response.FromValue(NumberResource.FromResponse(response), response); + } + + /// Create or replace Number. + /// Name of the account. + /// Telephone number in E.164 format. + /// The resource instance. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + /// Create or replace the details of a Number. + /// + public virtual Response CreateOrReplaceNumber(string accountName, string telephoneNumber, NumberResource resource, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + Argument.AssertNotNull(resource, nameof(resource)); + + using RequestContent content = resource.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateOrReplaceNumber(accountName, telephoneNumber, content, requestConditions, context); + return Response.FromValue(NumberResource.FromResponse(response), response); + } + + /// + /// [Protocol Method] Create or replace Number. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateOrReplaceNumberAsync(string accountName, string telephoneNumber, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.CreateOrReplaceNumber"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrReplaceNumberRequest(accountName, telephoneNumber, content, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create or replace Number. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CreateOrReplaceNumber(string accountName, string telephoneNumber, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.CreateOrReplaceNumber"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrReplaceNumberRequest(accountName, telephoneNumber, content, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete Number. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteNumberAsync(string accountName, string telephoneNumber, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.DeleteNumber"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteNumberRequest(accountName, telephoneNumber, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete Number. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Name of the account. + /// Telephone number in E.164 format. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response DeleteNumber(string accountName, string telephoneNumber, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(telephoneNumber, nameof(telephoneNumber)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.DeleteNumber"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteNumberRequest(accountName, telephoneNumber, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get Teams Usages. + /// Name of the account. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Teams capability plans on the specified account. + /// + public virtual async Task> GetTeamsCapabilityPlansAsync(string accountName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetTeamsCapabilityPlansAsync(accountName, context).ConfigureAwait(false); + return Response.FromValue(TeamsCapabilityPlans.FromResponse(response), response); + } + + /// Get Teams Usages. + /// Name of the account. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Teams capability plans on the specified account. + /// + public virtual Response GetTeamsCapabilityPlans(string accountName, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetTeamsCapabilityPlans(accountName, context); + return Response.FromValue(TeamsCapabilityPlans.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get Teams Usages. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetTeamsCapabilityPlansAsync(string accountName, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetTeamsCapabilityPlans"); + scope.Start(); + try + { + using HttpMessage message = CreateGetTeamsCapabilityPlansRequest(accountName, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get Teams Usages. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetTeamsCapabilityPlans(string accountName, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetTeamsCapabilityPlans"); + scope.Start(); + try + { + using HttpMessage message = CreateGetTeamsCapabilityPlansRequest(accountName, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get Teams Available Capabilities. + /// Name of the account. + /// List identifiers for a Number resource. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Teams Available Capabilities on the specified account. + /// + public virtual async Task> GetTeamsAvailableCapabilitiesAsync(string accountName, NumberIdentifiers body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetTeamsAvailableCapabilitiesAsync(accountName, content, context).ConfigureAwait(false); + return Response.FromValue(TeamsAvailableCapabilities.FromResponse(response), response); + } + + /// Get Teams Available Capabilities. + /// Name of the account. + /// List identifiers for a Number resource. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Teams Available Capabilities on the specified account. + /// + public virtual Response GetTeamsAvailableCapabilities(string accountName, NumberIdentifiers body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetTeamsAvailableCapabilities(accountName, content, context); + return Response.FromValue(TeamsAvailableCapabilities.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get Teams Available Capabilities. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetTeamsAvailableCapabilitiesAsync(string accountName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetTeamsAvailableCapabilities"); + scope.Start(); + try + { + using HttpMessage message = CreateGetTeamsAvailableCapabilitiesRequest(accountName, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get Teams Available Capabilities. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetTeamsAvailableCapabilities(string accountName, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetTeamsAvailableCapabilities"); + scope.Start(); + try + { + using HttpMessage message = CreateGetTeamsAvailableCapabilitiesRequest(accountName, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get Teams Civic Address. + /// Name of the account. + /// The ID of the civic address. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Get details of a specific Teams Civic Address using its ID. + /// + public virtual async Task> GetTeamsCivicAddressAsync(string accountName, string civicAddressId, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(civicAddressId, nameof(civicAddressId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetTeamsCivicAddressAsync(accountName, civicAddressId, requestConditions, context).ConfigureAwait(false); + return Response.FromValue(TeamsCivicAddressResource.FromResponse(response), response); + } + + /// Get Teams Civic Address. + /// Name of the account. + /// The ID of the civic address. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Get details of a specific Teams Civic Address using its ID. + /// + public virtual Response GetTeamsCivicAddress(string accountName, string civicAddressId, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(civicAddressId, nameof(civicAddressId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetTeamsCivicAddress(accountName, civicAddressId, requestConditions, context); + return Response.FromValue(TeamsCivicAddressResource.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get Teams Civic Address. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The ID of the civic address. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetTeamsCivicAddressAsync(string accountName, string civicAddressId, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(civicAddressId, nameof(civicAddressId)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetTeamsCivicAddress"); + scope.Start(); + try + { + using HttpMessage message = CreateGetTeamsCivicAddressRequest(accountName, civicAddressId, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get Teams Civic Address. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The ID of the civic address. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetTeamsCivicAddress(string accountName, string civicAddressId, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + Argument.AssertNotNullOrEmpty(civicAddressId, nameof(civicAddressId)); + + using var scope = ClientDiagnostics.CreateScope("Accounts.GetTeamsCivicAddress"); + scope.Start(); + try + { + using HttpMessage message = CreateGetTeamsCivicAddressRequest(accountName, civicAddressId, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get list of Accounts. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// Get list of Accounts with details. An Account represents an Enterprise or collection of users. + /// + public virtual AsyncPageable GetAccountResourcesAsync(int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetAccountResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetAccountResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => AccountResource.DeserializeAccountResource(e), ClientDiagnostics, _pipeline, "Accounts.GetAccountResources", "value", "nextLink", maxpagesize, context); + } + + /// Get list of Accounts. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// Get list of Accounts with details. An Account represents an Enterprise or collection of users. + /// + public virtual Pageable GetAccountResources(int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetAccountResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetAccountResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => AccountResource.DeserializeAccountResource(e), ClientDiagnostics, _pipeline, "Accounts.GetAccountResources", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get list of Accounts + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetAccountResourcesAsync(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetAccountResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetAccountResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Accounts.GetAccountResources", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get list of Accounts + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetAccountResources(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetAccountResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetAccountResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Accounts.GetAccountResources", "value", "nextLink", maxpagesize, context); + } + + /// Get Numbers. + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Numbers on the specified account. + /// + public virtual AsyncPageable GetNumbersAsync(string accountName, int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => NumberResource.DeserializeNumberResource(e), ClientDiagnostics, _pipeline, "Accounts.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + /// Get Numbers. + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Numbers on the specified account. + /// + public virtual Pageable GetNumbers(string accountName, int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => NumberResource.DeserializeNumberResource(e), ClientDiagnostics, _pipeline, "Accounts.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get Numbers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetNumbersAsync(string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Accounts.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get Numbers. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetNumbers(string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Accounts.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + /// Get Teams Civic Addresses. + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Teams Civic Addresses on the specified account. + /// + public virtual AsyncPageable GetTeamsCivicAddressesAsync(string accountName, int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetTeamsCivicAddressesRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetTeamsCivicAddressesNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => TeamsCivicAddressResource.DeserializeTeamsCivicAddressResource(e), ClientDiagnostics, _pipeline, "Accounts.GetTeamsCivicAddresses", "value", "nextLink", maxpagesize, context); + } + + /// Get Teams Civic Addresses. + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get a list of Teams Civic Addresses on the specified account. + /// + public virtual Pageable GetTeamsCivicAddresses(string accountName, int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetTeamsCivicAddressesRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetTeamsCivicAddressesNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => TeamsCivicAddressResource.DeserializeTeamsCivicAddressResource(e), ClientDiagnostics, _pipeline, "Accounts.GetTeamsCivicAddresses", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get Teams Civic Addresses. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetTeamsCivicAddressesAsync(string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetTeamsCivicAddressesRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetTeamsCivicAddressesNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Accounts.GetTeamsCivicAddresses", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get Teams Civic Addresses. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Name of the account. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetTeamsCivicAddresses(string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + Argument.AssertNotNullOrEmpty(accountName, nameof(accountName)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetTeamsCivicAddressesRequest(accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetTeamsCivicAddressesNextPageRequest(nextLink, accountName, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "Accounts.GetTeamsCivicAddresses", "value", "nextLink", maxpagesize, context); + } + + internal HttpMessage CreateGetAccountResourcesRequest(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (countRecords != null) + { + uri.AppendQuery("countRecords", countRecords.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetAccountResourceRequest(string accountName, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateCreateOrReplaceRequest(string accountName, RequestContent content, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteRequest(string accountName, bool? deleteNumbers, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendQuery("api-version", _apiVersion, true); + if (deleteNumbers != null) + { + uri.AppendQuery("deleteNumbers", deleteNumbers.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateCreateOrUpdateNumbersRequest(string accountName, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath(":createOrUpdateNumbers", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteNumbersRequest(string accountName, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath(":deleteNumbers", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetNumbersRequest(string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath("/numbers", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (countRecords != null) + { + uri.AppendQuery("countRecords", countRecords.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetNumberRequest(string accountName, string telephoneNumber, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath("/numbers/", false); + uri.AppendPath(telephoneNumber, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateCreateOrReplaceNumberRequest(string accountName, string telephoneNumber, RequestContent content, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Put; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath("/numbers/", false); + uri.AppendPath(telephoneNumber, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteNumberRequest(string accountName, string telephoneNumber, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath("/numbers/", false); + uri.AppendPath(telephoneNumber, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateGetTeamsCapabilityPlansRequest(string accountName, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath(":getTeamsCapabilityPlans", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + return message; + } + + internal HttpMessage CreateGetTeamsAvailableCapabilitiesRequest(string accountName, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath(":getTeamsAvailableCapabilities", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetTeamsCivicAddressesRequest(string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath("/teamsCivicAddresses", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (countRecords != null) + { + uri.AppendQuery("countRecords", countRecords.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetTeamsCivicAddressRequest(string accountName, string civicAddressId, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/accounts/", false); + uri.AppendPath(accountName, true); + uri.AppendPath("/teamsCivicAddresses/", false); + uri.AppendPath(civicAddressId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateGetAccountResourcesNextPageRequest(string nextLink, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetNumbersNextPageRequest(string nextLink, string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetTeamsCivicAddressesNextPageRequest(string nextLink, string accountName, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + private static ResponseClassifier _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.Serialization.cs new file mode 100644 index 000000000000..60112e274830 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class AzureOperatorCallProtectionAccountDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionAccountDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && Optional.IsDefined(NumberCount)) + { + writer.WritePropertyName("numberCount"u8); + writer.WriteNumberValue(NumberCount.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureOperatorCallProtectionAccountDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionAccountDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureOperatorCallProtectionAccountDetails(document.RootElement, options); + } + + internal static AzureOperatorCallProtectionAccountDetails DeserializeAzureOperatorCallProtectionAccountDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + long? numberCount = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("numberCount"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + numberCount = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureOperatorCallProtectionAccountDetails(enabled, numberCount, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionAccountDetails)} does not support writing '{options.Format}' format."); + } + } + + AzureOperatorCallProtectionAccountDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureOperatorCallProtectionAccountDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionAccountDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureOperatorCallProtectionAccountDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureOperatorCallProtectionAccountDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.cs new file mode 100644 index 000000000000..ff69e1df2883 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionAccountDetails.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Account details specific to Azure Operator Call Protection. + public partial class AzureOperatorCallProtectionAccountDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Account. + public AzureOperatorCallProtectionAccountDetails(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// Keeps track of any properties unknown to the library. + internal AzureOperatorCallProtectionAccountDetails(bool enabled, long? numberCount, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + NumberCount = numberCount; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureOperatorCallProtectionAccountDetails() + { + } + + /// Boolean indicating if the service is enabled on this Account. + public bool Enabled { get; set; } + /// The count of telephone numbers associated with this account that have this backend service enabled. + public long? NumberCount { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.Serialization.cs new file mode 100644 index 000000000000..d2d1843cf0e2 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class AzureOperatorCallProtectionNumberDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionNumberDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureOperatorCallProtectionNumberDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionNumberDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureOperatorCallProtectionNumberDetails(document.RootElement, options); + } + + internal static AzureOperatorCallProtectionNumberDetails DeserializeAzureOperatorCallProtectionNumberDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureOperatorCallProtectionNumberDetails(enabled, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionNumberDetails)} does not support writing '{options.Format}' format."); + } + } + + AzureOperatorCallProtectionNumberDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureOperatorCallProtectionNumberDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureOperatorCallProtectionNumberDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureOperatorCallProtectionNumberDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureOperatorCallProtectionNumberDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.cs new file mode 100644 index 000000000000..11c9d47dbe8a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/AzureOperatorCallProtectionNumberDetails.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Details for the Azure Operator Call Protection service on this Number. + public partial class AzureOperatorCallProtectionNumberDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + public AzureOperatorCallProtectionNumberDetails(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + /// Keeps track of any properties unknown to the library. + internal AzureOperatorCallProtectionNumberDetails(bool enabled, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureOperatorCallProtectionNumberDetails() + { + } + + /// Boolean indicating if the service is enabled on this Number. + public bool Enabled { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.Serialization.cs new file mode 100644 index 000000000000..945b3331764a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class BatchNumbers : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchNumbers)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("numbers"u8); + writer.WriteStartArray(); + foreach (var item in Numbers) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BatchNumbers IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchNumbers)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchNumbers(document.RootElement, options); + } + + internal static BatchNumbers DeserializeBatchNumbers(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList numbers = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("numbers"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(NumberResource.DeserializeNumberResource(item, options)); + } + numbers = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchNumbers(numbers, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(BatchNumbers)} does not support writing '{options.Format}' format."); + } + } + + BatchNumbers IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchNumbers(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchNumbers)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchNumbers FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchNumbers(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.cs new file mode 100644 index 000000000000..2ccea9bd7181 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbers.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// List of telephone numbers to be uploaded to an account via a PUT request. + public partial class BatchNumbers + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The list of numbers to upload. At most 100 can be uploaded in one request. + /// is null. + public BatchNumbers(IEnumerable numbers) + { + Argument.AssertNotNull(numbers, nameof(numbers)); + + Numbers = numbers.ToList(); + } + + /// Initializes a new instance of . + /// The list of numbers to upload. At most 100 can be uploaded in one request. + /// Keeps track of any properties unknown to the library. + internal BatchNumbers(IList numbers, IDictionary serializedAdditionalRawData) + { + Numbers = numbers; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal BatchNumbers() + { + } + + /// The list of numbers to upload. At most 100 can be uploaded in one request. + public IList Numbers { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.Serialization.cs new file mode 100644 index 000000000000..2a445ab90dd2 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class BatchNumbersDelete : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchNumbersDelete)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("numbers"u8); + writer.WriteStartArray(); + foreach (var item in Numbers) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BatchNumbersDelete IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchNumbersDelete)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchNumbersDelete(document.RootElement, options); + } + + internal static BatchNumbersDelete DeserializeBatchNumbersDelete(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList numbers = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("numbers"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(NumberIdentifier.DeserializeNumberIdentifier(item, options)); + } + numbers = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchNumbersDelete(numbers, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(BatchNumbersDelete)} does not support writing '{options.Format}' format."); + } + } + + BatchNumbersDelete IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchNumbersDelete(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchNumbersDelete)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchNumbersDelete FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchNumbersDelete(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.cs new file mode 100644 index 000000000000..f43d15b08138 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/BatchNumbersDelete.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// A list of telephone numbers to delete. + public partial class BatchNumbersDelete + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The list of number to delete. At most 100 can be deleted in one request. + /// is null. + public BatchNumbersDelete(IEnumerable numbers) + { + Argument.AssertNotNull(numbers, nameof(numbers)); + + Numbers = numbers.ToList(); + } + + /// Initializes a new instance of . + /// The list of number to delete. At most 100 can be deleted in one request. + /// Keeps track of any properties unknown to the library. + internal BatchNumbersDelete(IList numbers, IDictionary serializedAdditionalRawData) + { + Numbers = numbers; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal BatchNumbersDelete() + { + } + + /// The list of number to delete. At most 100 can be deleted in one request. + public IList Numbers { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.Serialization.cs new file mode 100644 index 000000000000..48c286660a56 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.Serialization.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class ContactDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContactDetails)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("fullName"u8); + writer.WriteStringValue(FullName); + } + if (options.Format != "W") + { + writer.WritePropertyName("email"u8); + writer.WriteStringValue(Email); + } + if (options.Format != "W" && Optional.IsDefined(TelephoneNumber)) + { + writer.WritePropertyName("telephoneNumber"u8); + writer.WriteStringValue(TelephoneNumber); + } + if (options.Format != "W" && Optional.IsDefined(CompanyName)) + { + writer.WritePropertyName("companyName"u8); + writer.WriteStringValue(CompanyName); + } + if (options.Format != "W" && Optional.IsDefined(CompanySize)) + { + writer.WritePropertyName("companySize"u8); + writer.WriteStringValue(CompanySize); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContactDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContactDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContactDetails(document.RootElement, options); + } + + internal static ContactDetails DeserializeContactDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fullName = default; + string email = default; + string telephoneNumber = default; + string companyName = default; + string companySize = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("fullName"u8)) + { + fullName = property.Value.GetString(); + continue; + } + if (property.NameEquals("email"u8)) + { + email = property.Value.GetString(); + continue; + } + if (property.NameEquals("telephoneNumber"u8)) + { + telephoneNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("companyName"u8)) + { + companyName = property.Value.GetString(); + continue; + } + if (property.NameEquals("companySize"u8)) + { + companySize = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContactDetails( + fullName, + email, + telephoneNumber, + companyName, + companySize, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContactDetails)} does not support writing '{options.Format}' format."); + } + } + + ContactDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContactDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContactDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContactDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContactDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.cs new file mode 100644 index 000000000000..237740f97fd7 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ContactDetails.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Contact details for an individual. + public partial class ContactDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ContactDetails() + { + } + + /// Initializes a new instance of . + /// The full name of the contact detail. + /// The email of the contact detail. + /// The telephone number of the contact detail. + /// The company name of the contact detail. + /// The company size of the contact detail. + /// Keeps track of any properties unknown to the library. + internal ContactDetails(string fullName, string email, string telephoneNumber, string companyName, string companySize, IDictionary serializedAdditionalRawData) + { + FullName = fullName; + Email = email; + TelephoneNumber = telephoneNumber; + CompanyName = companyName; + CompanySize = companySize; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The full name of the contact detail. + public string FullName { get; } + /// The email of the contact detail. + public string Email { get; } + /// The telephone number of the contact detail. + public string TelephoneNumber { get; } + /// The company name of the contact detail. + public string CompanyName { get; } + /// The company size of the contact detail. + public string CompanySize { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.Serialization.cs new file mode 100644 index 000000000000..8ef4c25e1188 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.Serialization.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class CustomerRelationship : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CustomerRelationship)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status); + } + if (options.Format != "W" && Optional.IsDefined(LastModifiedOn)) + { + writer.WritePropertyName("lastModifiedOn"u8); + writer.WriteStringValue(LastModifiedOn.Value, "O"); + } + if (Optional.IsDefined(Comment)) + { + writer.WritePropertyName("comment"u8); + writer.WriteStringValue(Comment); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CustomerRelationship IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CustomerRelationship)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCustomerRelationship(document.RootElement, options); + } + + internal static CustomerRelationship DeserializeCustomerRelationship(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string status = default; + DateTimeOffset? lastModifiedOn = default; + string comment = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("status"u8)) + { + status = property.Value.GetString(); + continue; + } + if (property.NameEquals("lastModifiedOn"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + lastModifiedOn = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("comment"u8)) + { + comment = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CustomerRelationship(status, lastModifiedOn, comment, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CustomerRelationship)} does not support writing '{options.Format}' format."); + } + } + + CustomerRelationship IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCustomerRelationship(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CustomerRelationship)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CustomerRelationship FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCustomerRelationship(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.cs new file mode 100644 index 000000000000..69c90759873f --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/CustomerRelationship.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Details of a customer relationship. + public partial class CustomerRelationship + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public CustomerRelationship() + { + } + + /// Initializes a new instance of . + /// The status of the customer relationship. + /// The time (ISO8601 format) when the customer relationship is last modified. + /// The comment of the customer relationship. + /// Keeps track of any properties unknown to the library. + internal CustomerRelationship(string status, DateTimeOffset? lastModifiedOn, string comment, IDictionary serializedAdditionalRawData) + { + Status = status; + LastModifiedOn = lastModifiedOn; + Comment = comment; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The status of the customer relationship. + public string Status { get; set; } + /// The time (ISO8601 format) when the customer relationship is last modified. + public DateTimeOffset? LastModifiedOn { get; } + /// The comment of the customer relationship. + public string Comment { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/Accounts.xml b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/Accounts.xml new file mode 100644 index 000000000000..2a83626ac5a4 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/Accounts.xml @@ -0,0 +1,973 @@ + + + + + +This sample shows how to call GetAccountResourceAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetAccountResourceAsync("contoso"); +]]> + + + +This sample shows how to call GetAccountResource. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetAccountResource("contoso"); +]]> + + + +This sample shows how to call GetAccountResourceAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetAccountResourceAsync("contoso", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +]]> + + + +This sample shows how to call GetAccountResource and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetAccountResource("contoso", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +]]> + + + +This sample shows how to call CreateOrReplaceAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +AccountResource resource = new AccountResource("contoso") +{ + CorrelationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + ServiceDetails = new AccountServiceDetails + { + TeamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + TeamsOperatorConnect = new TeamsOperatorConnectAccountDetails(true, true), + }, +}; +Response response = await client.CreateOrReplaceAsync("contoso", resource); +]]> + + + +This sample shows how to call CreateOrReplace. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +AccountResource resource = new AccountResource("contoso") +{ + CorrelationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + ServiceDetails = new AccountServiceDetails + { + TeamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + TeamsOperatorConnect = new TeamsOperatorConnectAccountDetails(true, true), + }, +}; +Response response = client.CreateOrReplace("contoso", resource); +]]> + + + +This sample shows how to call CreateOrReplaceAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + name = "contoso", + correlationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + serviceDetails = new + { + teamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + teamsOperatorConnect = new + { + enabled = true, + syncEnabled = true, + }, + }, +}); +Response response = await client.CreateOrReplaceAsync("contoso", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +]]> + + + +This sample shows how to call CreateOrReplace and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + name = "contoso", + correlationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + serviceDetails = new + { + teamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + teamsOperatorConnect = new + { + enabled = true, + syncEnabled = true, + }, + }, +}); +Response response = client.CreateOrReplace("contoso", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +]]> + + + +This sample shows how to call DeleteAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.DeleteAsync("contoso"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call Delete. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.Delete("contoso"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call CreateOrUpdateNumbersAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +BatchNumbers body = new BatchNumbers(new NumberResource[] +{ + new NumberResource("+15105850321", "contoso", new NumberServiceDetails + { + TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) + { + AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, + Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[]{"InboundCalling"}), + }, + }) + { + Configuration = new NumberConfiguration + { + CustomSipHeader = "contoso-commsgw", + }, + } +}); +Response response = await client.CreateOrUpdateNumbersAsync("contoso", body); +]]> + + + +This sample shows how to call CreateOrUpdateNumbers. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +BatchNumbers body = new BatchNumbers(new NumberResource[] +{ + new NumberResource("+15105850321", "contoso", new NumberServiceDetails + { + TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) + { + AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, + Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[]{"InboundCalling"}), + }, + }) + { + Configuration = new NumberConfiguration + { + CustomSipHeader = "contoso-commsgw", + }, + } +}); +Response response = client.CreateOrUpdateNumbers("contoso", body); +]]> + + + +This sample shows how to call CreateOrUpdateNumbersAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + numbers = new object[] + { + new + { + telephoneNumber = "+15105850321", + accountName = "contoso", + serviceDetails = new + { + teamsOperatorConnect = new + { + enabled = true, + assignmentStatus = "assigned", + configuration = new + { + usage = "CallingUserAssignment", + choosableCapabilities = new object[] + { + "InboundCalling" + }, + }, + }, + }, + configuration = new + { + customSipHeader = "contoso-commsgw", + }, + } + }, +}); +Response response = await client.CreateOrUpdateNumbersAsync("contoso", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("telephoneNumber").ToString()); +Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("accountName").ToString()); +Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("serviceDetails").ToString()); +]]> + + + +This sample shows how to call CreateOrUpdateNumbers and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + numbers = new object[] + { + new + { + telephoneNumber = "+15105850321", + accountName = "contoso", + serviceDetails = new + { + teamsOperatorConnect = new + { + enabled = true, + assignmentStatus = "assigned", + configuration = new + { + usage = "CallingUserAssignment", + choosableCapabilities = new object[] + { + "InboundCalling" + }, + }, + }, + }, + configuration = new + { + customSipHeader = "contoso-commsgw", + }, + } + }, +}); +Response response = client.CreateOrUpdateNumbers("contoso", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("telephoneNumber").ToString()); +Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("accountName").ToString()); +Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("serviceDetails").ToString()); +]]> + + + +This sample shows how to call DeleteNumbersAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +BatchNumbersDelete body = new BatchNumbersDelete(new NumberIdentifier[] +{ + new NumberIdentifier("+15105850321") +}); +Response response = await client.DeleteNumbersAsync("contoso", body); +]]> + + + +This sample shows how to call DeleteNumbers. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +BatchNumbersDelete body = new BatchNumbersDelete(new NumberIdentifier[] +{ + new NumberIdentifier("+15105850321") +}); +Response response = client.DeleteNumbers("contoso", body); +]]> + + + +This sample shows how to call DeleteNumbersAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + numbers = new object[] + { + new + { + telephoneNumber = "+15105850321", + } + }, +}); +Response response = await client.DeleteNumbersAsync("contoso", content); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call DeleteNumbers. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + numbers = new object[] + { + new + { + telephoneNumber = "+15105850321", + } + }, +}); +Response response = client.DeleteNumbers("contoso", content); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call GetNumberAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetNumberAsync("contoso", "+15105850321"); +]]> + + + +This sample shows how to call GetNumber. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetNumber("contoso", "+15105850321"); +]]> + + + +This sample shows how to call GetNumberAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetNumberAsync("contoso", "+15105850321", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); +Console.WriteLine(result.GetProperty("accountName").ToString()); +Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +]]> + + + +This sample shows how to call GetNumber and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetNumber("contoso", "+15105850321", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); +Console.WriteLine(result.GetProperty("accountName").ToString()); +Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +]]> + + + +This sample shows how to call CreateOrReplaceNumberAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +NumberResource resource = new NumberResource("+15105850321", "contoso", new NumberServiceDetails +{ + TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) + { + AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, + Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[] { "InboundCalling" }), + }, +}) +{ + Configuration = new NumberConfiguration + { + CustomSipHeader = "contoso-commsgw", + }, +}; +Response response = await client.CreateOrReplaceNumberAsync("contoso", "+15105850321", resource); +]]> + + + +This sample shows how to call CreateOrReplaceNumber. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +NumberResource resource = new NumberResource("+15105850321", "contoso", new NumberServiceDetails +{ + TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) + { + AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, + Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[] { "InboundCalling" }), + }, +}) +{ + Configuration = new NumberConfiguration + { + CustomSipHeader = "contoso-commsgw", + }, +}; +Response response = client.CreateOrReplaceNumber("contoso", "+15105850321", resource); +]]> + + + +This sample shows how to call CreateOrReplaceNumberAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + telephoneNumber = "+15105850321", + accountName = "contoso", + serviceDetails = new + { + teamsOperatorConnect = new + { + enabled = true, + assignmentStatus = "assigned", + configuration = new + { + usage = "CallingUserAssignment", + choosableCapabilities = new object[] + { + "InboundCalling" + }, + }, + }, + }, + configuration = new + { + customSipHeader = "contoso-commsgw", + }, +}); +Response response = await client.CreateOrReplaceNumberAsync("contoso", "+15105850321", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); +Console.WriteLine(result.GetProperty("accountName").ToString()); +Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +]]> + + + +This sample shows how to call CreateOrReplaceNumber and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + telephoneNumber = "+15105850321", + accountName = "contoso", + serviceDetails = new + { + teamsOperatorConnect = new + { + enabled = true, + assignmentStatus = "assigned", + configuration = new + { + usage = "CallingUserAssignment", + choosableCapabilities = new object[] + { + "InboundCalling" + }, + }, + }, + }, + configuration = new + { + customSipHeader = "contoso-commsgw", + }, +}); +Response response = client.CreateOrReplaceNumber("contoso", "+15105850321", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); +Console.WriteLine(result.GetProperty("accountName").ToString()); +Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +]]> + + + +This sample shows how to call DeleteNumberAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.DeleteNumberAsync("contoso", "+15105850321"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call DeleteNumber. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.DeleteNumber("contoso", "+15105850321"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call GetTeamsCapabilityPlansAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetTeamsCapabilityPlansAsync("contoso"); +]]> + + + +This sample shows how to call GetTeamsCapabilityPlans. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetTeamsCapabilityPlans("contoso"); +]]> + + + +This sample shows how to call GetTeamsCapabilityPlansAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetTeamsCapabilityPlansAsync("contoso", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("usage").ToString()); +Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("supportsTollFree").ToString()); +]]> + + + +This sample shows how to call GetTeamsCapabilityPlans and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetTeamsCapabilityPlans("contoso", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("usage").ToString()); +Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("supportsTollFree").ToString()); +]]> + + + +This sample shows how to call GetTeamsAvailableCapabilitiesAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +NumberIdentifiers body = new NumberIdentifiers(new NumberIdentifier[] +{ + new NumberIdentifier("+15105850321") +}); +Response response = await client.GetTeamsAvailableCapabilitiesAsync("contoso", body); +]]> + + + +This sample shows how to call GetTeamsAvailableCapabilities. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +NumberIdentifiers body = new NumberIdentifiers(new NumberIdentifier[] +{ + new NumberIdentifier("+15105850321") +}); +Response response = client.GetTeamsAvailableCapabilities("contoso", body); +]]> + + + +This sample shows how to call GetTeamsAvailableCapabilitiesAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + numbers = new object[] + { + new + { + telephoneNumber = "+15105850321", + } + }, +}); +Response response = await client.GetTeamsAvailableCapabilitiesAsync("contoso", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("availableCapabilities")[0].ToString()); +]]> + + + +This sample shows how to call GetTeamsAvailableCapabilities and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +using RequestContent content = RequestContent.Create(new +{ + numbers = new object[] + { + new + { + telephoneNumber = "+15105850321", + } + }, +}); +Response response = client.GetTeamsAvailableCapabilities("contoso", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("availableCapabilities")[0].ToString()); +]]> + + + +This sample shows how to call GetTeamsCivicAddressAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetTeamsCivicAddressAsync("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4"); +]]> + + + +This sample shows how to call GetTeamsCivicAddress. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetTeamsCivicAddress("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4"); +]]> + + + +This sample shows how to call GetTeamsCivicAddressAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = await client.GetTeamsCivicAddressAsync("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); +]]> + + + +This sample shows how to call GetTeamsCivicAddress and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +Response response = client.GetTeamsCivicAddress("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); +]]> + + + +This sample shows how to call GetAccountResourcesAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +await foreach (AccountResource item in client.GetAccountResourcesAsync()) +{ +} +]]> + + + +This sample shows how to call GetAccountResources. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +foreach (AccountResource item in client.GetAccountResources()) +{ +} +]]> + + + +This sample shows how to call GetAccountResourcesAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +await foreach (BinaryData item in client.GetAccountResourcesAsync(null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); +} +]]> + + + +This sample shows how to call GetAccountResources and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +foreach (BinaryData item in client.GetAccountResources(null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); +} +]]> + + + +This sample shows how to call GetNumbersAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +await foreach (NumberResource item in client.GetNumbersAsync("contoso")) +{ +} +]]> + + + +This sample shows how to call GetNumbers. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +foreach (NumberResource item in client.GetNumbers("contoso")) +{ +} +]]> + + + +This sample shows how to call GetNumbersAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +await foreach (BinaryData item in client.GetNumbersAsync("contoso", null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +} +]]> + + + +This sample shows how to call GetNumbers and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +foreach (BinaryData item in client.GetNumbers("contoso", null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +} +]]> + + + +This sample shows how to call GetTeamsCivicAddressesAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +await foreach (TeamsCivicAddressResource item in client.GetTeamsCivicAddressesAsync("contoso")) +{ +} +]]> + + + +This sample shows how to call GetTeamsCivicAddresses. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +foreach (TeamsCivicAddressResource item in client.GetTeamsCivicAddresses("contoso")) +{ +} +]]> + + + +This sample shows how to call GetTeamsCivicAddressesAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +await foreach (BinaryData item in client.GetTeamsCivicAddressesAsync("contoso", null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); +} +]]> + + + +This sample shows how to call GetTeamsCivicAddresses and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + +foreach (BinaryData item in client.GetTeamsCivicAddresses("contoso", null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); +} +]]> + + + \ No newline at end of file diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/TeamsRequestsForInformation.xml b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/TeamsRequestsForInformation.xml new file mode 100644 index 000000000000..53d58e32e58f --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/TeamsRequestsForInformation.xml @@ -0,0 +1,155 @@ + + + + + +This sample shows how to call GetRequestForInformationAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +Response response = await client.GetRequestForInformationAsync("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a"); +]]> + + + +This sample shows how to call GetRequestForInformation. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +Response response = client.GetRequestForInformation("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a"); +]]> + + + +This sample shows how to call GetRequestForInformationAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +Response response = await client.GetRequestForInformationAsync("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("tenantId").ToString()); +]]> + + + +This sample shows how to call GetRequestForInformation and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +Response response = client.GetRequestForInformation("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", null, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("tenantId").ToString()); +]]> + + + +This sample shows how to call CreateOrUpdateRequestForInformationAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +using RequestContent content = RequestContent.Create(new +{ + customerRelationship = new + { + status = "ConsentAcknowledged", + comment = "Consent has been accepted on 2024-01-12", + }, +}); +Response response = await client.CreateOrUpdateRequestForInformationAsync("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("tenantId").ToString()); +]]> + + + +This sample shows how to call CreateOrUpdateRequestForInformation and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +using RequestContent content = RequestContent.Create(new +{ + customerRelationship = new + { + status = "ConsentAcknowledged", + comment = "Consent has been accepted on 2024-01-12", + }, +}); +Response response = client.CreateOrUpdateRequestForInformation("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("tenantId").ToString()); +]]> + + + +This sample shows how to call GetRequestForInformationResourcesAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +await foreach (RequestForInformationResource item in client.GetRequestForInformationResourcesAsync()) +{ +} +]]> + + + +This sample shows how to call GetRequestForInformationResources. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +foreach (RequestForInformationResource item in client.GetRequestForInformationResources()) +{ +} +]]> + + + +This sample shows how to call GetRequestForInformationResourcesAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +await foreach (BinaryData item in client.GetRequestForInformationResourcesAsync(null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); +} +]]> + + + +This sample shows how to call GetRequestForInformationResources and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + +foreach (BinaryData item in client.GetRequestForInformationResources(null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); +} +]]> + + + \ No newline at end of file diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/VoiceServicesClient.xml b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/VoiceServicesClient.xml new file mode 100644 index 000000000000..d8e87e5c00c2 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Docs/VoiceServicesClient.xml @@ -0,0 +1,65 @@ + + + + + +This sample shows how to call GetNumbersAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + +await foreach (NumberResource item in client.GetNumbersAsync()) +{ +} +]]> + + + +This sample shows how to call GetNumbers. +"); +TokenCredential credential = new DefaultAzureCredential(); +VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + +foreach (NumberResource item in client.GetNumbers()) +{ +} +]]> + + + +This sample shows how to call GetNumbersAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + +await foreach (BinaryData item in client.GetNumbersAsync(null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +} +]]> + + + +This sample shows how to call GetNumbers and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + +foreach (BinaryData item in client.GetNumbers(null, null, null, null, true, null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); +} +]]> + + + \ No newline at end of file diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Argument.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..17d6ef6480c9 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..b48d55916b5b --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingList.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..5758e18aa7f5 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.VoiceServices.Provisioning +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..d6ff749a2011 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Optional.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..4fbe60521490 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Microsoft.VoiceServices.Provisioning +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..b361c3c8ad5f --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.Serialization.cs new file mode 100644 index 000000000000..16975097e3e7 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.Serialization.cs @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class Location : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Location)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (options.Format != "W") + { + writer.WritePropertyName("civicAddressId"u8); + writer.WriteStringValue(CivicAddressId); + } + if (options.Format != "W" && Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (options.Format != "W" && Optional.IsDefined(AdditionalInfo)) + { + writer.WritePropertyName("additionalInfo"u8); + writer.WriteStringValue(AdditionalInfo); + } + if (options.Format != "W" && Optional.IsDefined(IsDefault)) + { + writer.WritePropertyName("isDefault"u8); + writer.WriteBooleanValue(IsDefault.Value); + } + if (options.Format != "W" && Optional.IsDefined(Elin)) + { + writer.WritePropertyName("elin"u8); + writer.WriteStringValue(Elin); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Location IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Location)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLocation(document.RootElement, options); + } + + internal static Location DeserializeLocation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + string civicAddressId = default; + string description = default; + string additionalInfo = default; + bool? isDefault = default; + string elin = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("civicAddressId"u8)) + { + civicAddressId = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("additionalInfo"u8)) + { + additionalInfo = property.Value.GetString(); + continue; + } + if (property.NameEquals("isDefault"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + isDefault = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("elin"u8)) + { + elin = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Location( + id, + civicAddressId, + description, + additionalInfo, + isDefault, + elin, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Location)} does not support writing '{options.Format}' format."); + } + } + + Location IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLocation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Location)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Location FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLocation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.cs new file mode 100644 index 000000000000..99fffa04d81a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/Location.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// A location used by Team Operator Connect or Teams Phone Mobile telephone numbers. + public partial class Location + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal Location() + { + } + + /// Initializes a new instance of . + /// The ID of the location. + /// The civic address ID of the location. + /// The description of the location. + /// The additional information of the location. + /// Flag indicating whether the location is default or not. + /// The elin (Emergency Location Identification Number) of the location. + /// Keeps track of any properties unknown to the library. + internal Location(string id, string civicAddressId, string description, string additionalInfo, bool? isDefault, string elin, IDictionary serializedAdditionalRawData) + { + Id = id; + CivicAddressId = civicAddressId; + Description = description; + AdditionalInfo = additionalInfo; + IsDefault = isDefault; + Elin = elin; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The ID of the location. + public string Id { get; } + /// The civic address ID of the location. + public string CivicAddressId { get; } + /// The description of the location. + public string Description { get; } + /// The additional information of the location. + public string AdditionalInfo { get; } + /// Flag indicating whether the location is default or not. + public bool? IsDefault { get; } + /// The elin (Emergency Location Identification Number) of the location. + public string Elin { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningClientBuilderExtensions.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningClientBuilderExtensions.cs new file mode 100644 index 000000000000..290795f6348f --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core.Extensions; +using Microsoft.VoiceServices.Provisioning; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class MicrosoftVoiceServicesProvisioningClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// Service host. + public static IAzureClientBuilder AddVoiceServicesClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new VoiceServicesClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddVoiceServicesClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningModelFactory.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningModelFactory.cs new file mode 100644 index 000000000000..b678118022f8 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/MicrosoftVoiceServicesProvisioningModelFactory.cs @@ -0,0 +1,365 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Model factory for models. + public static partial class MicrosoftVoiceServicesProvisioningModelFactory + { + /// Initializes a new instance of . + /// The status of the provisioning action associated with this resource. + /// Any errors pertaining to the provisioning of this resource. + /// Telephone number in E.164 format. + /// Name of the account. Can only contain letters, numbers, underscores and dashes, and is case-sensitive. Can be up to 100 characters in length. + /// Configuration of the individual backend services for this number. + /// Configuration for this number. + /// A new instance for mocking. + public static NumberResource NumberResource(ServiceProvisioningStatus? serviceProvisioningStatus = null, IEnumerable serviceProvisioningErrors = null, string telephoneNumber = null, string accountName = null, NumberServiceDetails serviceDetails = null, NumberConfiguration configuration = null) + { + serviceProvisioningErrors ??= new List(); + + return new NumberResource( + serviceProvisioningStatus, + serviceProvisioningErrors?.ToList(), + telephoneNumber, + accountName, + serviceDetails, + configuration, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The usage for this telephone number. + /// The choosable capabilities for this telephone number. + /// The acquired capabilities for this telephone number. + /// The available capabilities for this telephone number. + /// The additional usages for this telephone number. + /// The ID of the civic address to be used as the emergency address for this telephone number. + /// The ID of the location to be used as the emergency address for this telephone number. + /// If the enterprise is allowed to update the address for this telephone number. + /// The country code to be displayed with this telephone number. + /// A new instance for mocking. + public static TeamsOperatorConnectNumberConfig TeamsOperatorConnectNumberConfig(string usage = null, IEnumerable choosableCapabilities = null, IEnumerable acquiredCapabilities = null, IEnumerable availableCapabilities = null, IEnumerable additionalUsages = null, string civicAddressId = null, string locationId = null, bool? allowTenantAddressUpdate = null, string displayedCountryCode = null) + { + choosableCapabilities ??= new List(); + acquiredCapabilities ??= new List(); + availableCapabilities ??= new List(); + additionalUsages ??= new List(); + + return new TeamsOperatorConnectNumberConfig( + usage, + choosableCapabilities?.ToList(), + acquiredCapabilities?.ToList(), + availableCapabilities?.ToList(), + additionalUsages?.ToList(), + civicAddressId, + locationId, + allowTenantAddressUpdate, + displayedCountryCode, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The usage for this telephone number. + /// The choosable capabilities for this telephone number. + /// The acquired capabilities for this telephone number. + /// The available capabilities for this telephone number. + /// The additional usages for this telephone number. + /// The ID of the civic address to be used as the emergency address for this telephone number. + /// The ID of the location to be used as the emergency address for this telephone number. + /// If the enterprise is allowed to update the address for this telephone number. + /// The country code to be displayed with this telephone number. + /// A new instance for mocking. + public static TeamsPhoneMobileNumberConfig TeamsPhoneMobileNumberConfig(string usage = null, IEnumerable choosableCapabilities = null, IEnumerable acquiredCapabilities = null, IEnumerable availableCapabilities = null, IEnumerable additionalUsages = null, string civicAddressId = null, string locationId = null, bool? allowTenantAddressUpdate = null, string displayedCountryCode = null) + { + choosableCapabilities ??= new List(); + acquiredCapabilities ??= new List(); + availableCapabilities ??= new List(); + additionalUsages ??= new List(); + + return new TeamsPhoneMobileNumberConfig( + usage, + choosableCapabilities?.ToList(), + acquiredCapabilities?.ToList(), + availableCapabilities?.ToList(), + additionalUsages?.ToList(), + civicAddressId, + locationId, + allowTenantAddressUpdate, + displayedCountryCode, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the provisioning action associated with this resource. + /// Any errors pertaining to the provisioning of this resource. + /// The ID of the Request for Information. + /// The Teams tenant ID which generated this Request for Information. + /// The name of the account associated with this Request for Information. + /// Will always be 'teams'. + /// The operator ID of the operator consent. + /// The status of the operator consent. + /// The time (ISO8601 format) when the operator consent is created. + /// The time (ISO8601 format) when the operator consent is last modified. + /// The list of consented countries. + /// The list of tenant contacts. + /// The customer relationship of the operator consent. + /// A new instance for mocking. + public static RequestForInformationResource RequestForInformationResource(ServiceProvisioningStatus? serviceProvisioningStatus = null, IEnumerable serviceProvisioningErrors = null, string id = null, string tenantId = null, string accountName = null, string productContext = null, string operatorId = null, TeamsConsentStatus? status = null, DateTimeOffset? consentedOn = null, DateTimeOffset? lastModifiedOn = null, IEnumerable consentedCountries = null, IEnumerable contacts = null, CustomerRelationship customerRelationship = null) + { + serviceProvisioningErrors ??= new List(); + consentedCountries ??= new List(); + contacts ??= new List(); + + return new RequestForInformationResource( + serviceProvisioningStatus, + serviceProvisioningErrors?.ToList(), + id, + tenantId, + accountName, + productContext, + operatorId, + status, + consentedOn, + lastModifiedOn, + consentedCountries?.ToList(), + contacts?.ToList(), + customerRelationship, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The full name of the contact detail. + /// The email of the contact detail. + /// The telephone number of the contact detail. + /// The company name of the contact detail. + /// The company size of the contact detail. + /// A new instance for mocking. + public static ContactDetails ContactDetails(string fullName = null, string email = null, string telephoneNumber = null, string companyName = null, string companySize = null) + { + return new ContactDetails( + fullName, + email, + telephoneNumber, + companyName, + companySize, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the customer relationship. + /// The time (ISO8601 format) when the customer relationship is last modified. + /// The comment of the customer relationship. + /// A new instance for mocking. + public static CustomerRelationship CustomerRelationship(string status = null, DateTimeOffset? lastModifiedOn = null, string comment = null) + { + return new CustomerRelationship(status, lastModifiedOn, comment, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The status of the provisioning action associated with this resource. + /// Any errors pertaining to the provisioning of this resource. + /// Name of the account. + /// A user defined identifier used for correlating with external systems. + /// The details of the account. + /// A new instance for mocking. + public static AccountResource AccountResource(ServiceProvisioningStatus? serviceProvisioningStatus = null, IEnumerable serviceProvisioningErrors = null, string name = null, string correlationId = null, AccountServiceDetails serviceDetails = null) + { + serviceProvisioningErrors ??= new List(); + + return new AccountResource( + serviceProvisioningStatus, + serviceProvisioningErrors?.ToList(), + name, + correlationId, + serviceDetails, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// A new instance for mocking. + public static TeamsOperatorConnectAccountDetails TeamsOperatorConnectAccountDetails(bool syncEnabled = default, bool enabled = default, long? numberCount = null) + { + return new TeamsOperatorConnectAccountDetails(syncEnabled, enabled, numberCount, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// The configuration for Teams Direct Routing on this account. + /// The provisioning status of the domains. + /// A new instance for mocking. + public static TeamsDirectRoutingAccountDetails TeamsDirectRoutingAccountDetails(bool syncEnabled = default, bool enabled = default, long? numberCount = null, TeamsDirectRoutingAccountConfig configuration = null, TeamsDirectRoutingSubdomainProvisioningStatus subdomainStatus = default) + { + return new TeamsDirectRoutingAccountDetails( + syncEnabled, + enabled, + numberCount, + configuration, + subdomainStatus, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// A new instance for mocking. + public static TeamsPhoneMobileAccountDetails TeamsPhoneMobileAccountDetails(bool syncEnabled = default, bool enabled = default, long? numberCount = null) + { + return new TeamsPhoneMobileAccountDetails(syncEnabled, enabled, numberCount, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// A new instance for mocking. + public static ZoomPhoneCloudPeeringAccountDetails ZoomPhoneCloudPeeringAccountDetails(bool syncEnabled = default, bool enabled = default, long? numberCount = null) + { + return new ZoomPhoneCloudPeeringAccountDetails(syncEnabled, enabled, numberCount, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// A new instance for mocking. + public static AzureOperatorCallProtectionAccountDetails AzureOperatorCallProtectionAccountDetails(bool enabled = default, long? numberCount = null) + { + return new AzureOperatorCallProtectionAccountDetails(enabled, numberCount, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A list of telephone number upload usages. + /// A new instance for mocking. + public static TeamsCapabilityPlans TeamsCapabilityPlans(IEnumerable capabilityPlans = null) + { + capabilityPlans ??= new List(); + + return new TeamsCapabilityPlans(capabilityPlans?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The capability plan name. + /// The offer types available. + /// The telephone number usage. + /// Mandatory capabilities for telephone numbers. + /// Choosable capabilities for telephone numbers. + /// Boolean indicating if Toll free is supported. + /// A new instance for mocking. + public static TeamsCapabilityPlan TeamsCapabilityPlan(string name = null, IEnumerable offerTypes = null, string usage = null, IEnumerable mandatoryCapabilities = null, IEnumerable choosableCapabilities = null, bool supportsTollFree = default) + { + offerTypes ??= new List(); + mandatoryCapabilities ??= new List(); + choosableCapabilities ??= new List(); + + return new TeamsCapabilityPlan( + name, + offerTypes?.ToList(), + usage, + mandatoryCapabilities?.ToList(), + choosableCapabilities?.ToList(), + supportsTollFree, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The available capabilities for the numbers specified with Operator Connect or Teams Phone Mobile services enabled. + /// A new instance for mocking. + public static TeamsAvailableCapabilities TeamsAvailableCapabilities(IEnumerable availableCapabilities = null) + { + availableCapabilities ??= new List(); + + return new TeamsAvailableCapabilities(availableCapabilities?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The ID of the civic address. + /// The country of the civic address. + /// The house number of the civic address. + /// The house number suffix of the civic address. + /// The pre directional of the civic address. + /// The street name of the civic address. + /// The street suffix of the civic address. + /// The post directional of the civic address. + /// The state or province of the civic address. + /// The county or district of the civic address. + /// The city or town of the civic address. + /// The city or town alias of the civic address. + /// The postal or zip code of the civic address. + /// The description of the civic address. + /// The company name of the civic address. + /// The company ID of the civic address. + /// The default location ID of the civic address. + /// The validation status of the civic address. + /// The customer tenant ID of the civic address. + /// The partner ID of the civic address. + /// The list of locations associated with the civic address. + /// The latitude of the civic address. + /// The longitude of the civic address. + /// A new instance for mocking. + public static TeamsCivicAddressResource TeamsCivicAddressResource(string id = null, string country = null, string houseNumber = null, string houseNumberSuffix = null, string preDirectional = null, string streetName = null, string streetSuffix = null, string postDirectional = null, string stateOrProvince = null, string countyOrDistrict = null, string cityOrTown = null, string cityOrTownAlias = null, string postalOrZipCode = null, string description = null, string companyName = null, string companyId = null, string defaultLocationId = null, ValidationStatus? validationStatus = null, string tenantId = null, string partnerId = null, IEnumerable locations = null, string latitude = null, string longitude = null) + { + locations ??= new List(); + + return new TeamsCivicAddressResource( + id, + country, + houseNumber, + houseNumberSuffix, + preDirectional, + streetName, + streetSuffix, + postDirectional, + stateOrProvince, + countyOrDistrict, + cityOrTown, + cityOrTownAlias, + postalOrZipCode, + description, + companyName, + companyId, + defaultLocationId, + validationStatus, + tenantId, + partnerId, + locations?.ToList(), + latitude, + longitude, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The ID of the location. + /// The civic address ID of the location. + /// The description of the location. + /// The additional information of the location. + /// Flag indicating whether the location is default or not. + /// The elin (Emergency Location Identification Number) of the location. + /// A new instance for mocking. + public static Location Location(string id = null, string civicAddressId = null, string description = null, string additionalInfo = null, bool? isDefault = null, string elin = null) + { + return new Location( + id, + civicAddressId, + description, + additionalInfo, + isDefault, + elin, + serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.Serialization.cs new file mode 100644 index 000000000000..67300d7fd307 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.Serialization.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class NumberConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberConfiguration)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(CustomSipHeader)) + { + writer.WritePropertyName("customSipHeader"u8); + writer.WriteStringValue(CustomSipHeader); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberConfiguration(document.RootElement, options); + } + + internal static NumberConfiguration DeserializeNumberConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string customSipHeader = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("customSipHeader"u8)) + { + customSipHeader = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberConfiguration(customSipHeader, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberConfiguration)} does not support writing '{options.Format}' format."); + } + } + + NumberConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.cs new file mode 100644 index 000000000000..5711b959329c --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberConfiguration.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Configuration for this number. + public partial class NumberConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public NumberConfiguration() + { + } + + /// Initializes a new instance of . + /// Contents of the custom SIP header to use with this number. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. The name of the custom header is set as part of the provisioning platform configuration on Azure Communications Gateway. + /// Keeps track of any properties unknown to the library. + internal NumberConfiguration(string customSipHeader, IDictionary serializedAdditionalRawData) + { + CustomSipHeader = customSipHeader; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Contents of the custom SIP header to use with this number. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. The name of the custom header is set as part of the provisioning platform configuration on Azure Communications Gateway. + public string CustomSipHeader { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.Serialization.cs new file mode 100644 index 000000000000..04742a06a01a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class NumberIdentifier : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberIdentifier)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("telephoneNumber"u8); + writer.WriteStringValue(TelephoneNumber); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberIdentifier IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberIdentifier)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberIdentifier(document.RootElement, options); + } + + internal static NumberIdentifier DeserializeNumberIdentifier(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string telephoneNumber = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("telephoneNumber"u8)) + { + telephoneNumber = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberIdentifier(telephoneNumber, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberIdentifier)} does not support writing '{options.Format}' format."); + } + } + + NumberIdentifier IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberIdentifier(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberIdentifier)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberIdentifier FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberIdentifier(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.cs new file mode 100644 index 000000000000..90e20f6dc44b --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifier.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// An identifier, used to identify a Number resource. + public partial class NumberIdentifier + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Telephone number in E.164 format. + /// is null. + public NumberIdentifier(string telephoneNumber) + { + Argument.AssertNotNull(telephoneNumber, nameof(telephoneNumber)); + + TelephoneNumber = telephoneNumber; + } + + /// Initializes a new instance of . + /// Telephone number in E.164 format. + /// Keeps track of any properties unknown to the library. + internal NumberIdentifier(string telephoneNumber, IDictionary serializedAdditionalRawData) + { + TelephoneNumber = telephoneNumber; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NumberIdentifier() + { + } + + /// Telephone number in E.164 format. + public string TelephoneNumber { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.Serialization.cs new file mode 100644 index 000000000000..fde7c5360600 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class NumberIdentifiers : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberIdentifiers)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("numbers"u8); + writer.WriteStartArray(); + foreach (var item in Numbers) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberIdentifiers IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberIdentifiers)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberIdentifiers(document.RootElement, options); + } + + internal static NumberIdentifiers DeserializeNumberIdentifiers(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList numbers = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("numbers"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(NumberIdentifier.DeserializeNumberIdentifier(item, options)); + } + numbers = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberIdentifiers(numbers, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberIdentifiers)} does not support writing '{options.Format}' format."); + } + } + + NumberIdentifiers IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberIdentifiers(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberIdentifiers)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberIdentifiers FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberIdentifiers(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.cs new file mode 100644 index 000000000000..3a161cce2892 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberIdentifiers.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// A list identifiers for a Number resource. + public partial class NumberIdentifiers + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Array containing a list of identifiers for Number resources. + /// is null. + public NumberIdentifiers(IEnumerable numbers) + { + Argument.AssertNotNull(numbers, nameof(numbers)); + + Numbers = numbers.ToList(); + } + + /// Initializes a new instance of . + /// Array containing a list of identifiers for Number resources. + /// Keeps track of any properties unknown to the library. + internal NumberIdentifiers(IList numbers, IDictionary serializedAdditionalRawData) + { + Numbers = numbers; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NumberIdentifiers() + { + } + + /// Array containing a list of identifiers for Number resources. + public IList Numbers { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.Serialization.cs new file mode 100644 index 000000000000..35ed45a0156a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.Serialization.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class NumberResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberResource)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ServiceProvisioningStatus)) + { + writer.WritePropertyName("serviceProvisioningStatus"u8); + writer.WriteStringValue(ServiceProvisioningStatus.Value.ToString()); + } + if (options.Format != "W" && Optional.IsCollectionDefined(ServiceProvisioningErrors)) + { + writer.WritePropertyName("serviceProvisioningErrors"u8); + writer.WriteStartArray(); + foreach (var item in ServiceProvisioningErrors) + { + JsonSerializer.Serialize(writer, item); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("telephoneNumber"u8); + writer.WriteStringValue(TelephoneNumber); + writer.WritePropertyName("accountName"u8); + writer.WriteStringValue(AccountName); + writer.WritePropertyName("serviceDetails"u8); + writer.WriteObjectValue(ServiceDetails, options); + if (Optional.IsDefined(Configuration)) + { + writer.WritePropertyName("configuration"u8); + writer.WriteObjectValue(Configuration, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberResource(document.RootElement, options); + } + + internal static NumberResource DeserializeNumberResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ServiceProvisioningStatus? serviceProvisioningStatus = default; + IReadOnlyList serviceProvisioningErrors = default; + string telephoneNumber = default; + string accountName = default; + NumberServiceDetails serviceDetails = default; + NumberConfiguration configuration = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("serviceProvisioningStatus"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + serviceProvisioningStatus = new ServiceProvisioningStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("serviceProvisioningErrors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(JsonSerializer.Deserialize(item.GetRawText())); + } + serviceProvisioningErrors = array; + continue; + } + if (property.NameEquals("telephoneNumber"u8)) + { + telephoneNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("accountName"u8)) + { + accountName = property.Value.GetString(); + continue; + } + if (property.NameEquals("serviceDetails"u8)) + { + serviceDetails = NumberServiceDetails.DeserializeNumberServiceDetails(property.Value, options); + continue; + } + if (property.NameEquals("configuration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + configuration = NumberConfiguration.DeserializeNumberConfiguration(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberResource( + serviceProvisioningStatus, + serviceProvisioningErrors ?? new ChangeTrackingList(), + telephoneNumber, + accountName, + serviceDetails, + configuration, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberResource)} does not support writing '{options.Format}' format."); + } + } + + NumberResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.cs new file mode 100644 index 000000000000..ff23d578e442 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberResource.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// The configuration for a telephone number provisioned in Azure Communications Gateway. + public partial class NumberResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Telephone number in E.164 format. + /// Name of the account. Can only contain letters, numbers, underscores and dashes, and is case-sensitive. Can be up to 100 characters in length. + /// Configuration of the individual backend services for this number. + /// , or is null. + public NumberResource(string telephoneNumber, string accountName, NumberServiceDetails serviceDetails) + { + Argument.AssertNotNull(telephoneNumber, nameof(telephoneNumber)); + Argument.AssertNotNull(accountName, nameof(accountName)); + Argument.AssertNotNull(serviceDetails, nameof(serviceDetails)); + + ServiceProvisioningErrors = new ChangeTrackingList(); + TelephoneNumber = telephoneNumber; + AccountName = accountName; + ServiceDetails = serviceDetails; + } + + /// Initializes a new instance of . + /// The status of the provisioning action associated with this resource. + /// Any errors pertaining to the provisioning of this resource. + /// Telephone number in E.164 format. + /// Name of the account. Can only contain letters, numbers, underscores and dashes, and is case-sensitive. Can be up to 100 characters in length. + /// Configuration of the individual backend services for this number. + /// Configuration for this number. + /// Keeps track of any properties unknown to the library. + internal NumberResource(ServiceProvisioningStatus? serviceProvisioningStatus, IReadOnlyList serviceProvisioningErrors, string telephoneNumber, string accountName, NumberServiceDetails serviceDetails, NumberConfiguration configuration, IDictionary serializedAdditionalRawData) + { + ServiceProvisioningStatus = serviceProvisioningStatus; + ServiceProvisioningErrors = serviceProvisioningErrors; + TelephoneNumber = telephoneNumber; + AccountName = accountName; + ServiceDetails = serviceDetails; + Configuration = configuration; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NumberResource() + { + } + + /// The status of the provisioning action associated with this resource. + public ServiceProvisioningStatus? ServiceProvisioningStatus { get; } + /// Any errors pertaining to the provisioning of this resource. + public IReadOnlyList ServiceProvisioningErrors { get; } + /// Telephone number in E.164 format. + public string TelephoneNumber { get; set; } + /// Name of the account. Can only contain letters, numbers, underscores and dashes, and is case-sensitive. Can be up to 100 characters in length. + public string AccountName { get; set; } + /// Configuration of the individual backend services for this number. + public NumberServiceDetails ServiceDetails { get; set; } + /// Configuration for this number. + public NumberConfiguration Configuration { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.Serialization.cs new file mode 100644 index 000000000000..325208a03c24 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.Serialization.cs @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class NumberServiceDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberServiceDetails)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(TeamsOperatorConnect)) + { + writer.WritePropertyName("teamsOperatorConnect"u8); + writer.WriteObjectValue(TeamsOperatorConnect, options); + } + if (Optional.IsDefined(TeamsDirectRouting)) + { + writer.WritePropertyName("teamsDirectRouting"u8); + writer.WriteObjectValue(TeamsDirectRouting, options); + } + if (Optional.IsDefined(TeamsPhoneMobile)) + { + writer.WritePropertyName("teamsPhoneMobile"u8); + writer.WriteObjectValue(TeamsPhoneMobile, options); + } + if (Optional.IsDefined(ZoomPhoneCloudPeering)) + { + writer.WritePropertyName("zoomPhoneCloudPeering"u8); + writer.WriteObjectValue(ZoomPhoneCloudPeering, options); + } + if (Optional.IsDefined(AzureOperatorCallProtection)) + { + writer.WritePropertyName("azureOperatorCallProtection"u8); + writer.WriteObjectValue(AzureOperatorCallProtection, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberServiceDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberServiceDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberServiceDetails(document.RootElement, options); + } + + internal static NumberServiceDetails DeserializeNumberServiceDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + TeamsOperatorConnectNumberDetails teamsOperatorConnect = default; + TeamsDirectRoutingNumberDetails teamsDirectRouting = default; + TeamsPhoneMobileNumberDetails teamsPhoneMobile = default; + ZoomPhoneCloudPeeringNumberDetails zoomPhoneCloudPeering = default; + AzureOperatorCallProtectionNumberDetails azureOperatorCallProtection = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("teamsOperatorConnect"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + teamsOperatorConnect = TeamsOperatorConnectNumberDetails.DeserializeTeamsOperatorConnectNumberDetails(property.Value, options); + continue; + } + if (property.NameEquals("teamsDirectRouting"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + teamsDirectRouting = TeamsDirectRoutingNumberDetails.DeserializeTeamsDirectRoutingNumberDetails(property.Value, options); + continue; + } + if (property.NameEquals("teamsPhoneMobile"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + teamsPhoneMobile = TeamsPhoneMobileNumberDetails.DeserializeTeamsPhoneMobileNumberDetails(property.Value, options); + continue; + } + if (property.NameEquals("zoomPhoneCloudPeering"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + zoomPhoneCloudPeering = ZoomPhoneCloudPeeringNumberDetails.DeserializeZoomPhoneCloudPeeringNumberDetails(property.Value, options); + continue; + } + if (property.NameEquals("azureOperatorCallProtection"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + azureOperatorCallProtection = AzureOperatorCallProtectionNumberDetails.DeserializeAzureOperatorCallProtectionNumberDetails(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberServiceDetails( + teamsOperatorConnect, + teamsDirectRouting, + teamsPhoneMobile, + zoomPhoneCloudPeering, + azureOperatorCallProtection, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberServiceDetails)} does not support writing '{options.Format}' format."); + } + } + + NumberServiceDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberServiceDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberServiceDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberServiceDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberServiceDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.cs new file mode 100644 index 000000000000..888147b1e60e --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/NumberServiceDetails.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Configuration of backend services for a telephone number. + public partial class NumberServiceDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public NumberServiceDetails() + { + } + + /// Initializes a new instance of . + /// Details for the Teams Operator Connect service on this Number. + /// Details for the Teams Direct Routing service on this Number. + /// Details for the Teams Phone Mobile service on this Number. + /// Details for the Zoom Phone Cloud Peering service on this Number. + /// Details for the Azure Operator Call Protection service on this Number. + /// Keeps track of any properties unknown to the library. + internal NumberServiceDetails(TeamsOperatorConnectNumberDetails teamsOperatorConnect, TeamsDirectRoutingNumberDetails teamsDirectRouting, TeamsPhoneMobileNumberDetails teamsPhoneMobile, ZoomPhoneCloudPeeringNumberDetails zoomPhoneCloudPeering, AzureOperatorCallProtectionNumberDetails azureOperatorCallProtection, IDictionary serializedAdditionalRawData) + { + TeamsOperatorConnect = teamsOperatorConnect; + TeamsDirectRouting = teamsDirectRouting; + TeamsPhoneMobile = teamsPhoneMobile; + ZoomPhoneCloudPeering = zoomPhoneCloudPeering; + AzureOperatorCallProtection = azureOperatorCallProtection; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Details for the Teams Operator Connect service on this Number. + public TeamsOperatorConnectNumberDetails TeamsOperatorConnect { get; set; } + /// Details for the Teams Direct Routing service on this Number. + public TeamsDirectRoutingNumberDetails TeamsDirectRouting { get; set; } + /// Details for the Teams Phone Mobile service on this Number. + public TeamsPhoneMobileNumberDetails TeamsPhoneMobile { get; set; } + /// Details for the Zoom Phone Cloud Peering service on this Number. + public ZoomPhoneCloudPeeringNumberDetails ZoomPhoneCloudPeering { get; set; } + /// Details for the Azure Operator Call Protection service on this Number. + public AzureOperatorCallProtectionNumberDetails AzureOperatorCallProtection { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.Serialization.cs new file mode 100644 index 000000000000..5ddd51ee40d2 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.Serialization.cs @@ -0,0 +1,354 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class RequestForInformationResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RequestForInformationResource)} does not support writing '{format}' format."); + } + + if (options.Format != "W" && Optional.IsDefined(ServiceProvisioningStatus)) + { + writer.WritePropertyName("serviceProvisioningStatus"u8); + writer.WriteStringValue(ServiceProvisioningStatus.Value.ToString()); + } + if (options.Format != "W" && Optional.IsCollectionDefined(ServiceProvisioningErrors)) + { + writer.WritePropertyName("serviceProvisioningErrors"u8); + writer.WriteStartArray(); + foreach (var item in ServiceProvisioningErrors) + { + JsonSerializer.Serialize(writer, item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && Optional.IsDefined(Id)) + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (options.Format != "W") + { + writer.WritePropertyName("tenantId"u8); + writer.WriteStringValue(TenantId); + } + if (options.Format != "W" && Optional.IsDefined(AccountName)) + { + writer.WritePropertyName("accountName"u8); + writer.WriteStringValue(AccountName); + } + if (options.Format != "W" && Optional.IsDefined(ProductContext)) + { + writer.WritePropertyName("productContext"u8); + writer.WriteStringValue(ProductContext); + } + if (options.Format != "W" && Optional.IsDefined(OperatorId)) + { + writer.WritePropertyName("operatorId"u8); + writer.WriteStringValue(OperatorId); + } + if (options.Format != "W" && Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (options.Format != "W" && Optional.IsDefined(ConsentedOn)) + { + writer.WritePropertyName("consentedOn"u8); + writer.WriteStringValue(ConsentedOn.Value, "O"); + } + if (options.Format != "W" && Optional.IsDefined(LastModifiedOn)) + { + writer.WritePropertyName("lastModifiedOn"u8); + writer.WriteStringValue(LastModifiedOn.Value, "O"); + } + if (options.Format != "W" && Optional.IsCollectionDefined(ConsentedCountries)) + { + writer.WritePropertyName("consentedCountries"u8); + writer.WriteStartArray(); + foreach (var item in ConsentedCountries) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && Optional.IsCollectionDefined(Contacts)) + { + writer.WritePropertyName("contacts"u8); + writer.WriteStartArray(); + foreach (var item in Contacts) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(CustomerRelationship)) + { + writer.WritePropertyName("customerRelationship"u8); + writer.WriteObjectValue(CustomerRelationship, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RequestForInformationResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RequestForInformationResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRequestForInformationResource(document.RootElement, options); + } + + internal static RequestForInformationResource DeserializeRequestForInformationResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ServiceProvisioningStatus? serviceProvisioningStatus = default; + IReadOnlyList serviceProvisioningErrors = default; + string id = default; + string tenantId = default; + string accountName = default; + string productContext = default; + string operatorId = default; + TeamsConsentStatus? status = default; + DateTimeOffset? consentedOn = default; + DateTimeOffset? lastModifiedOn = default; + IReadOnlyList consentedCountries = default; + IReadOnlyList contacts = default; + CustomerRelationship customerRelationship = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("serviceProvisioningStatus"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + serviceProvisioningStatus = new ServiceProvisioningStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("serviceProvisioningErrors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(JsonSerializer.Deserialize(item.GetRawText())); + } + serviceProvisioningErrors = array; + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("tenantId"u8)) + { + tenantId = property.Value.GetString(); + continue; + } + if (property.NameEquals("accountName"u8)) + { + accountName = property.Value.GetString(); + continue; + } + if (property.NameEquals("productContext"u8)) + { + productContext = property.Value.GetString(); + continue; + } + if (property.NameEquals("operatorId"u8)) + { + operatorId = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new TeamsConsentStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("consentedOn"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + consentedOn = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("lastModifiedOn"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + lastModifiedOn = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("consentedCountries"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + consentedCountries = array; + continue; + } + if (property.NameEquals("contacts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ContactDetails.DeserializeContactDetails(item, options)); + } + contacts = array; + continue; + } + if (property.NameEquals("customerRelationship"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + customerRelationship = CustomerRelationship.DeserializeCustomerRelationship(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RequestForInformationResource( + serviceProvisioningStatus, + serviceProvisioningErrors ?? new ChangeTrackingList(), + id, + tenantId, + accountName, + productContext, + operatorId, + status, + consentedOn, + lastModifiedOn, + consentedCountries ?? new ChangeTrackingList(), + contacts ?? new ChangeTrackingList(), + customerRelationship, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RequestForInformationResource)} does not support writing '{options.Format}' format."); + } + } + + RequestForInformationResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRequestForInformationResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RequestForInformationResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RequestForInformationResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRequestForInformationResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.cs new file mode 100644 index 000000000000..804e8d1e426d --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/RequestForInformationResource.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// The configuration for a telephone number provisioned in ACG. + public partial class RequestForInformationResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public RequestForInformationResource() + { + ServiceProvisioningErrors = new ChangeTrackingList(); + ConsentedCountries = new ChangeTrackingList(); + Contacts = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The status of the provisioning action associated with this resource. + /// Any errors pertaining to the provisioning of this resource. + /// The ID of the Request for Information. + /// The Teams tenant ID which generated this Request for Information. + /// The name of the account associated with this Request for Information. + /// Will always be 'teams'. + /// The operator ID of the operator consent. + /// The status of the operator consent. + /// The time (ISO8601 format) when the operator consent is created. + /// The time (ISO8601 format) when the operator consent is last modified. + /// The list of consented countries. + /// The list of tenant contacts. + /// The customer relationship of the operator consent. + /// Keeps track of any properties unknown to the library. + internal RequestForInformationResource(ServiceProvisioningStatus? serviceProvisioningStatus, IReadOnlyList serviceProvisioningErrors, string id, string tenantId, string accountName, string productContext, string operatorId, TeamsConsentStatus? status, DateTimeOffset? consentedOn, DateTimeOffset? lastModifiedOn, IReadOnlyList consentedCountries, IReadOnlyList contacts, CustomerRelationship customerRelationship, IDictionary serializedAdditionalRawData) + { + ServiceProvisioningStatus = serviceProvisioningStatus; + ServiceProvisioningErrors = serviceProvisioningErrors; + Id = id; + TenantId = tenantId; + AccountName = accountName; + ProductContext = productContext; + OperatorId = operatorId; + Status = status; + ConsentedOn = consentedOn; + LastModifiedOn = lastModifiedOn; + ConsentedCountries = consentedCountries; + Contacts = contacts; + CustomerRelationship = customerRelationship; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The status of the provisioning action associated with this resource. + public ServiceProvisioningStatus? ServiceProvisioningStatus { get; } + /// Any errors pertaining to the provisioning of this resource. + public IReadOnlyList ServiceProvisioningErrors { get; } + /// The ID of the Request for Information. + public string Id { get; } + /// The Teams tenant ID which generated this Request for Information. + public string TenantId { get; } + /// The name of the account associated with this Request for Information. + public string AccountName { get; } + /// Will always be 'teams'. + public string ProductContext { get; } + /// The operator ID of the operator consent. + public string OperatorId { get; } + /// The status of the operator consent. + public TeamsConsentStatus? Status { get; } + /// The time (ISO8601 format) when the operator consent is created. + public DateTimeOffset? ConsentedOn { get; } + /// The time (ISO8601 format) when the operator consent is last modified. + public DateTimeOffset? LastModifiedOn { get; } + /// The list of consented countries. + public IReadOnlyList ConsentedCountries { get; } + /// The list of tenant contacts. + public IReadOnlyList Contacts { get; } + /// The customer relationship of the operator consent. + public CustomerRelationship CustomerRelationship { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ServiceProvisioningStatus.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ServiceProvisioningStatus.cs new file mode 100644 index 000000000000..6064748b96e2 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ServiceProvisioningStatus.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// The provisioning states of an object on any relevant backend service. + public readonly partial struct ServiceProvisioningStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ServiceProvisioningStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string PendingValue = "pending"; + private const string SyncedValue = "synced"; + private const string FailedValue = "failed"; + + /// The object is pending provisioning. + public static ServiceProvisioningStatus Pending { get; } = new ServiceProvisioningStatus(PendingValue); + /// The object has been synced with the relevant backend service. + public static ServiceProvisioningStatus Synced { get; } = new ServiceProvisioningStatus(SyncedValue); + /// The object provisioning operation failed with the relevant backend service. + public static ServiceProvisioningStatus Failed { get; } = new ServiceProvisioningStatus(FailedValue); + /// Determines if two values are the same. + public static bool operator ==(ServiceProvisioningStatus left, ServiceProvisioningStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ServiceProvisioningStatus left, ServiceProvisioningStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ServiceProvisioningStatus(string value) => new ServiceProvisioningStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ServiceProvisioningStatus other && Equals(other); + /// + public bool Equals(ServiceProvisioningStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.Serialization.cs new file mode 100644 index 000000000000..d061cf60dc08 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.Serialization.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsAvailableCapabilities : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsAvailableCapabilities)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("availableCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in AvailableCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsAvailableCapabilities IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsAvailableCapabilities)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsAvailableCapabilities(document.RootElement, options); + } + + internal static TeamsAvailableCapabilities DeserializeTeamsAvailableCapabilities(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList availableCapabilities = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("availableCapabilities"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + availableCapabilities = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsAvailableCapabilities(availableCapabilities, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsAvailableCapabilities)} does not support writing '{options.Format}' format."); + } + } + + TeamsAvailableCapabilities IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsAvailableCapabilities(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsAvailableCapabilities)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsAvailableCapabilities FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsAvailableCapabilities(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.cs new file mode 100644 index 000000000000..1efbe9849568 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsAvailableCapabilities.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// The Teams capabilities available for numbers with Operator Connect or Teams Phone Mobile services enabled. + public partial class TeamsAvailableCapabilities + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal TeamsAvailableCapabilities() + { + AvailableCapabilities = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The available capabilities for the numbers specified with Operator Connect or Teams Phone Mobile services enabled. + /// Keeps track of any properties unknown to the library. + internal TeamsAvailableCapabilities(IReadOnlyList availableCapabilities, IDictionary serializedAdditionalRawData) + { + AvailableCapabilities = availableCapabilities; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The available capabilities for the numbers specified with Operator Connect or Teams Phone Mobile services enabled. + public IReadOnlyList AvailableCapabilities { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.Serialization.cs new file mode 100644 index 000000000000..ca6d0e96f264 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.Serialization.cs @@ -0,0 +1,250 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsCapabilityPlan : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsCapabilityPlan)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (options.Format != "W" && Optional.IsCollectionDefined(OfferTypes)) + { + writer.WritePropertyName("offerTypes"u8); + writer.WriteStartArray(); + foreach (var item in OfferTypes) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W") + { + writer.WritePropertyName("usage"u8); + writer.WriteStringValue(Usage); + } + if (options.Format != "W" && Optional.IsCollectionDefined(MandatoryCapabilities)) + { + writer.WritePropertyName("mandatoryCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in MandatoryCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && Optional.IsCollectionDefined(ChoosableCapabilities)) + { + writer.WritePropertyName("choosableCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in ChoosableCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W") + { + writer.WritePropertyName("supportsTollFree"u8); + writer.WriteBooleanValue(SupportsTollFree); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsCapabilityPlan IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsCapabilityPlan)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsCapabilityPlan(document.RootElement, options); + } + + internal static TeamsCapabilityPlan DeserializeTeamsCapabilityPlan(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + IReadOnlyList offerTypes = default; + string usage = default; + IReadOnlyList mandatoryCapabilities = default; + IReadOnlyList choosableCapabilities = default; + bool supportsTollFree = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("offerTypes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + offerTypes = array; + continue; + } + if (property.NameEquals("usage"u8)) + { + usage = property.Value.GetString(); + continue; + } + if (property.NameEquals("mandatoryCapabilities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + mandatoryCapabilities = array; + continue; + } + if (property.NameEquals("choosableCapabilities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + choosableCapabilities = array; + continue; + } + if (property.NameEquals("supportsTollFree"u8)) + { + supportsTollFree = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsCapabilityPlan( + name, + offerTypes ?? new ChangeTrackingList(), + usage, + mandatoryCapabilities ?? new ChangeTrackingList(), + choosableCapabilities ?? new ChangeTrackingList(), + supportsTollFree, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsCapabilityPlan)} does not support writing '{options.Format}' format."); + } + } + + TeamsCapabilityPlan IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsCapabilityPlan(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsCapabilityPlan)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsCapabilityPlan FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsCapabilityPlan(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.cs new file mode 100644 index 000000000000..daa8b4f3ecfd --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlan.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// A teams capability plan for a given usage. + public partial class TeamsCapabilityPlan + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal TeamsCapabilityPlan() + { + OfferTypes = new ChangeTrackingList(); + MandatoryCapabilities = new ChangeTrackingList(); + ChoosableCapabilities = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The capability plan name. + /// The offer types available. + /// The telephone number usage. + /// Mandatory capabilities for telephone numbers. + /// Choosable capabilities for telephone numbers. + /// Boolean indicating if Toll free is supported. + /// Keeps track of any properties unknown to the library. + internal TeamsCapabilityPlan(string name, IReadOnlyList offerTypes, string usage, IReadOnlyList mandatoryCapabilities, IReadOnlyList choosableCapabilities, bool supportsTollFree, IDictionary serializedAdditionalRawData) + { + Name = name; + OfferTypes = offerTypes; + Usage = usage; + MandatoryCapabilities = mandatoryCapabilities; + ChoosableCapabilities = choosableCapabilities; + SupportsTollFree = supportsTollFree; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The capability plan name. + public string Name { get; } + /// The offer types available. + public IReadOnlyList OfferTypes { get; } + /// The telephone number usage. + public string Usage { get; } + /// Mandatory capabilities for telephone numbers. + public IReadOnlyList MandatoryCapabilities { get; } + /// Choosable capabilities for telephone numbers. + public IReadOnlyList ChoosableCapabilities { get; } + /// Boolean indicating if Toll free is supported. + public bool SupportsTollFree { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.Serialization.cs new file mode 100644 index 000000000000..379d45d5b4ff --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.Serialization.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsCapabilityPlans : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsCapabilityPlans)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("capabilityPlans"u8); + writer.WriteStartArray(); + foreach (var item in CapabilityPlans) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsCapabilityPlans IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsCapabilityPlans)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsCapabilityPlans(document.RootElement, options); + } + + internal static TeamsCapabilityPlans DeserializeTeamsCapabilityPlans(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList capabilityPlans = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("capabilityPlans"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(TeamsCapabilityPlan.DeserializeTeamsCapabilityPlan(item, options)); + } + capabilityPlans = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsCapabilityPlans(capabilityPlans, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsCapabilityPlans)} does not support writing '{options.Format}' format."); + } + } + + TeamsCapabilityPlans IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsCapabilityPlans(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsCapabilityPlans)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsCapabilityPlans FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsCapabilityPlans(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.cs new file mode 100644 index 000000000000..ed8ec02e8a47 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCapabilityPlans.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// The Teams telephone number upload usages for this account. + public partial class TeamsCapabilityPlans + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal TeamsCapabilityPlans() + { + CapabilityPlans = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A list of telephone number upload usages. + /// Keeps track of any properties unknown to the library. + internal TeamsCapabilityPlans(IReadOnlyList capabilityPlans, IDictionary serializedAdditionalRawData) + { + CapabilityPlans = capabilityPlans; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of telephone number upload usages. + public IReadOnlyList CapabilityPlans { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.Serialization.cs new file mode 100644 index 000000000000..898e36ab6a7a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.Serialization.cs @@ -0,0 +1,430 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsCivicAddressResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsCivicAddressResource)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + if (options.Format != "W" && Optional.IsDefined(Country)) + { + writer.WritePropertyName("country"u8); + writer.WriteStringValue(Country); + } + if (options.Format != "W" && Optional.IsDefined(HouseNumber)) + { + writer.WritePropertyName("houseNumber"u8); + writer.WriteStringValue(HouseNumber); + } + if (options.Format != "W" && Optional.IsDefined(HouseNumberSuffix)) + { + writer.WritePropertyName("houseNumberSuffix"u8); + writer.WriteStringValue(HouseNumberSuffix); + } + if (options.Format != "W" && Optional.IsDefined(PreDirectional)) + { + writer.WritePropertyName("preDirectional"u8); + writer.WriteStringValue(PreDirectional); + } + if (options.Format != "W" && Optional.IsDefined(StreetName)) + { + writer.WritePropertyName("streetName"u8); + writer.WriteStringValue(StreetName); + } + if (options.Format != "W" && Optional.IsDefined(StreetSuffix)) + { + writer.WritePropertyName("streetSuffix"u8); + writer.WriteStringValue(StreetSuffix); + } + if (options.Format != "W" && Optional.IsDefined(PostDirectional)) + { + writer.WritePropertyName("postDirectional"u8); + writer.WriteStringValue(PostDirectional); + } + if (options.Format != "W" && Optional.IsDefined(StateOrProvince)) + { + writer.WritePropertyName("stateOrProvince"u8); + writer.WriteStringValue(StateOrProvince); + } + if (options.Format != "W" && Optional.IsDefined(CountyOrDistrict)) + { + writer.WritePropertyName("countyOrDistrict"u8); + writer.WriteStringValue(CountyOrDistrict); + } + if (options.Format != "W" && Optional.IsDefined(CityOrTown)) + { + writer.WritePropertyName("cityOrTown"u8); + writer.WriteStringValue(CityOrTown); + } + if (options.Format != "W" && Optional.IsDefined(CityOrTownAlias)) + { + writer.WritePropertyName("cityOrTownAlias"u8); + writer.WriteStringValue(CityOrTownAlias); + } + if (options.Format != "W" && Optional.IsDefined(PostalOrZipCode)) + { + writer.WritePropertyName("postalOrZipCode"u8); + writer.WriteStringValue(PostalOrZipCode); + } + if (options.Format != "W" && Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (options.Format != "W" && Optional.IsDefined(CompanyName)) + { + writer.WritePropertyName("companyName"u8); + writer.WriteStringValue(CompanyName); + } + if (options.Format != "W" && Optional.IsDefined(CompanyId)) + { + writer.WritePropertyName("companyId"u8); + writer.WriteStringValue(CompanyId); + } + if (options.Format != "W") + { + writer.WritePropertyName("defaultLocationId"u8); + writer.WriteStringValue(DefaultLocationId); + } + if (options.Format != "W" && Optional.IsDefined(ValidationStatus)) + { + writer.WritePropertyName("validationStatus"u8); + writer.WriteStringValue(ValidationStatus.Value.ToString()); + } + if (options.Format != "W" && Optional.IsDefined(TenantId)) + { + writer.WritePropertyName("tenantId"u8); + writer.WriteStringValue(TenantId); + } + if (options.Format != "W" && Optional.IsDefined(PartnerId)) + { + writer.WritePropertyName("partnerId"u8); + writer.WriteStringValue(PartnerId); + } + if (options.Format != "W" && Optional.IsCollectionDefined(Locations)) + { + writer.WritePropertyName("locations"u8); + writer.WriteStartArray(); + foreach (var item in Locations) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && Optional.IsDefined(Latitude)) + { + writer.WritePropertyName("latitude"u8); + writer.WriteStringValue(Latitude); + } + if (options.Format != "W" && Optional.IsDefined(Longitude)) + { + writer.WritePropertyName("longitude"u8); + writer.WriteStringValue(Longitude); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsCivicAddressResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsCivicAddressResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsCivicAddressResource(document.RootElement, options); + } + + internal static TeamsCivicAddressResource DeserializeTeamsCivicAddressResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + string country = default; + string houseNumber = default; + string houseNumberSuffix = default; + string preDirectional = default; + string streetName = default; + string streetSuffix = default; + string postDirectional = default; + string stateOrProvince = default; + string countyOrDistrict = default; + string cityOrTown = default; + string cityOrTownAlias = default; + string postalOrZipCode = default; + string description = default; + string companyName = default; + string companyId = default; + string defaultLocationId = default; + ValidationStatus? validationStatus = default; + string tenantId = default; + string partnerId = default; + IReadOnlyList locations = default; + string latitude = default; + string longitude = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("country"u8)) + { + country = property.Value.GetString(); + continue; + } + if (property.NameEquals("houseNumber"u8)) + { + houseNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("houseNumberSuffix"u8)) + { + houseNumberSuffix = property.Value.GetString(); + continue; + } + if (property.NameEquals("preDirectional"u8)) + { + preDirectional = property.Value.GetString(); + continue; + } + if (property.NameEquals("streetName"u8)) + { + streetName = property.Value.GetString(); + continue; + } + if (property.NameEquals("streetSuffix"u8)) + { + streetSuffix = property.Value.GetString(); + continue; + } + if (property.NameEquals("postDirectional"u8)) + { + postDirectional = property.Value.GetString(); + continue; + } + if (property.NameEquals("stateOrProvince"u8)) + { + stateOrProvince = property.Value.GetString(); + continue; + } + if (property.NameEquals("countyOrDistrict"u8)) + { + countyOrDistrict = property.Value.GetString(); + continue; + } + if (property.NameEquals("cityOrTown"u8)) + { + cityOrTown = property.Value.GetString(); + continue; + } + if (property.NameEquals("cityOrTownAlias"u8)) + { + cityOrTownAlias = property.Value.GetString(); + continue; + } + if (property.NameEquals("postalOrZipCode"u8)) + { + postalOrZipCode = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("companyName"u8)) + { + companyName = property.Value.GetString(); + continue; + } + if (property.NameEquals("companyId"u8)) + { + companyId = property.Value.GetString(); + continue; + } + if (property.NameEquals("defaultLocationId"u8)) + { + defaultLocationId = property.Value.GetString(); + continue; + } + if (property.NameEquals("validationStatus"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + validationStatus = new ValidationStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("tenantId"u8)) + { + tenantId = property.Value.GetString(); + continue; + } + if (property.NameEquals("partnerId"u8)) + { + partnerId = property.Value.GetString(); + continue; + } + if (property.NameEquals("locations"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(Location.DeserializeLocation(item, options)); + } + locations = array; + continue; + } + if (property.NameEquals("latitude"u8)) + { + latitude = property.Value.GetString(); + continue; + } + if (property.NameEquals("longitude"u8)) + { + longitude = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsCivicAddressResource( + id, + country, + houseNumber, + houseNumberSuffix, + preDirectional, + streetName, + streetSuffix, + postDirectional, + stateOrProvince, + countyOrDistrict, + cityOrTown, + cityOrTownAlias, + postalOrZipCode, + description, + companyName, + companyId, + defaultLocationId, + validationStatus, + tenantId, + partnerId, + locations ?? new ChangeTrackingList(), + latitude, + longitude, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsCivicAddressResource)} does not support writing '{options.Format}' format."); + } + } + + TeamsCivicAddressResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsCivicAddressResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsCivicAddressResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsCivicAddressResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsCivicAddressResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.cs new file mode 100644 index 000000000000..b6b0b5d0f462 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsCivicAddressResource.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// A civic address available for Teams Operator Connect or Teams Phone Mobile users. + public partial class TeamsCivicAddressResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal TeamsCivicAddressResource() + { + Locations = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The ID of the civic address. + /// The country of the civic address. + /// The house number of the civic address. + /// The house number suffix of the civic address. + /// The pre directional of the civic address. + /// The street name of the civic address. + /// The street suffix of the civic address. + /// The post directional of the civic address. + /// The state or province of the civic address. + /// The county or district of the civic address. + /// The city or town of the civic address. + /// The city or town alias of the civic address. + /// The postal or zip code of the civic address. + /// The description of the civic address. + /// The company name of the civic address. + /// The company ID of the civic address. + /// The default location ID of the civic address. + /// The validation status of the civic address. + /// The customer tenant ID of the civic address. + /// The partner ID of the civic address. + /// The list of locations associated with the civic address. + /// The latitude of the civic address. + /// The longitude of the civic address. + /// Keeps track of any properties unknown to the library. + internal TeamsCivicAddressResource(string id, string country, string houseNumber, string houseNumberSuffix, string preDirectional, string streetName, string streetSuffix, string postDirectional, string stateOrProvince, string countyOrDistrict, string cityOrTown, string cityOrTownAlias, string postalOrZipCode, string description, string companyName, string companyId, string defaultLocationId, ValidationStatus? validationStatus, string tenantId, string partnerId, IReadOnlyList locations, string latitude, string longitude, IDictionary serializedAdditionalRawData) + { + Id = id; + Country = country; + HouseNumber = houseNumber; + HouseNumberSuffix = houseNumberSuffix; + PreDirectional = preDirectional; + StreetName = streetName; + StreetSuffix = streetSuffix; + PostDirectional = postDirectional; + StateOrProvince = stateOrProvince; + CountyOrDistrict = countyOrDistrict; + CityOrTown = cityOrTown; + CityOrTownAlias = cityOrTownAlias; + PostalOrZipCode = postalOrZipCode; + Description = description; + CompanyName = companyName; + CompanyId = companyId; + DefaultLocationId = defaultLocationId; + ValidationStatus = validationStatus; + TenantId = tenantId; + PartnerId = partnerId; + Locations = locations; + Latitude = latitude; + Longitude = longitude; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The ID of the civic address. + public string Id { get; } + /// The country of the civic address. + public string Country { get; } + /// The house number of the civic address. + public string HouseNumber { get; } + /// The house number suffix of the civic address. + public string HouseNumberSuffix { get; } + /// The pre directional of the civic address. + public string PreDirectional { get; } + /// The street name of the civic address. + public string StreetName { get; } + /// The street suffix of the civic address. + public string StreetSuffix { get; } + /// The post directional of the civic address. + public string PostDirectional { get; } + /// The state or province of the civic address. + public string StateOrProvince { get; } + /// The county or district of the civic address. + public string CountyOrDistrict { get; } + /// The city or town of the civic address. + public string CityOrTown { get; } + /// The city or town alias of the civic address. + public string CityOrTownAlias { get; } + /// The postal or zip code of the civic address. + public string PostalOrZipCode { get; } + /// The description of the civic address. + public string Description { get; } + /// The company name of the civic address. + public string CompanyName { get; } + /// The company ID of the civic address. + public string CompanyId { get; } + /// The default location ID of the civic address. + public string DefaultLocationId { get; } + /// The validation status of the civic address. + public ValidationStatus? ValidationStatus { get; } + /// The customer tenant ID of the civic address. + public string TenantId { get; } + /// The partner ID of the civic address. + public string PartnerId { get; } + /// The list of locations associated with the civic address. + public IReadOnlyList Locations { get; } + /// The latitude of the civic address. + public string Latitude { get; } + /// The longitude of the civic address. + public string Longitude { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsConsentStatus.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsConsentStatus.cs new file mode 100644 index 000000000000..650aa5b506b7 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsConsentStatus.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// The possible state for an Operator Consent. + public readonly partial struct TeamsConsentStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TeamsConsentStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ActiveValue = "active"; + private const string SuspendedValue = "suspended"; + private const string RemovedValue = "removed"; + + /// The Operator Consent is active. + public static TeamsConsentStatus Active { get; } = new TeamsConsentStatus(ActiveValue); + /// The Operator Consent is suspended. + public static TeamsConsentStatus Suspended { get; } = new TeamsConsentStatus(SuspendedValue); + /// The Operator Consent is removed. + public static TeamsConsentStatus Removed { get; } = new TeamsConsentStatus(RemovedValue); + /// Determines if two values are the same. + public static bool operator ==(TeamsConsentStatus left, TeamsConsentStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TeamsConsentStatus left, TeamsConsentStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TeamsConsentStatus(string value) => new TeamsConsentStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TeamsConsentStatus other && Equals(other); + /// + public bool Equals(TeamsConsentStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.Serialization.cs new file mode 100644 index 000000000000..ce6900636d16 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsDirectRoutingAccountConfig : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountConfig)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("callScreening"u8); + writer.WriteBooleanValue(CallScreening); + writer.WritePropertyName("subdomain"u8); + writer.WriteStringValue(Subdomain); + writer.WritePropertyName("subdomainTokens"u8); + writer.WriteObjectValue(SubdomainTokens, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsDirectRoutingAccountConfig IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountConfig)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsDirectRoutingAccountConfig(document.RootElement, options); + } + + internal static TeamsDirectRoutingAccountConfig DeserializeTeamsDirectRoutingAccountConfig(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool callScreening = default; + string subdomain = default; + TeamsDirectRoutingSubdomainTokens subdomainTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("callScreening"u8)) + { + callScreening = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("subdomain"u8)) + { + subdomain = property.Value.GetString(); + continue; + } + if (property.NameEquals("subdomainTokens"u8)) + { + subdomainTokens = TeamsDirectRoutingSubdomainTokens.DeserializeTeamsDirectRoutingSubdomainTokens(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsDirectRoutingAccountConfig(callScreening, subdomain, subdomainTokens, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountConfig)} does not support writing '{options.Format}' format."); + } + } + + TeamsDirectRoutingAccountConfig IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingAccountConfig(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountConfig)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsDirectRoutingAccountConfig FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingAccountConfig(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.cs new file mode 100644 index 000000000000..d074b9e7b99d --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountConfig.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Configuration specific to Teams Direct Routing. + public partial class TeamsDirectRoutingAccountConfig + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Enables/disables caller ID screening for the account. Caller ID screening is enabled by default. + /// Enterprise-specific domain name label. Can only contain letters, numbers, underscores and dashes. Can be up to 10 characters in length. + /// DNS TXT value for the Direct Routing regions, as provided by the customer from their Microsoft 365 Admin Center. + /// or is null. + public TeamsDirectRoutingAccountConfig(bool callScreening, string subdomain, TeamsDirectRoutingSubdomainTokens subdomainTokens) + { + Argument.AssertNotNull(subdomain, nameof(subdomain)); + Argument.AssertNotNull(subdomainTokens, nameof(subdomainTokens)); + + CallScreening = callScreening; + Subdomain = subdomain; + SubdomainTokens = subdomainTokens; + } + + /// Initializes a new instance of . + /// Enables/disables caller ID screening for the account. Caller ID screening is enabled by default. + /// Enterprise-specific domain name label. Can only contain letters, numbers, underscores and dashes. Can be up to 10 characters in length. + /// DNS TXT value for the Direct Routing regions, as provided by the customer from their Microsoft 365 Admin Center. + /// Keeps track of any properties unknown to the library. + internal TeamsDirectRoutingAccountConfig(bool callScreening, string subdomain, TeamsDirectRoutingSubdomainTokens subdomainTokens, IDictionary serializedAdditionalRawData) + { + CallScreening = callScreening; + Subdomain = subdomain; + SubdomainTokens = subdomainTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsDirectRoutingAccountConfig() + { + } + + /// Enables/disables caller ID screening for the account. Caller ID screening is enabled by default. + public bool CallScreening { get; set; } + /// Enterprise-specific domain name label. Can only contain letters, numbers, underscores and dashes. Can be up to 10 characters in length. + public string Subdomain { get; set; } + /// DNS TXT value for the Direct Routing regions, as provided by the customer from their Microsoft 365 Admin Center. + public TeamsDirectRoutingSubdomainTokens SubdomainTokens { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.Serialization.cs new file mode 100644 index 000000000000..6a29589a2657 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.Serialization.cs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsDirectRoutingAccountDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("syncEnabled"u8); + writer.WriteBooleanValue(SyncEnabled); + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && Optional.IsDefined(NumberCount)) + { + writer.WritePropertyName("numberCount"u8); + writer.WriteNumberValue(NumberCount.Value); + } + if (Optional.IsDefined(Configuration)) + { + writer.WritePropertyName("configuration"u8); + writer.WriteObjectValue(Configuration, options); + } + if (options.Format != "W") + { + writer.WritePropertyName("subdomainStatus"u8); + writer.WriteStringValue(SubdomainStatus.ToString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsDirectRoutingAccountDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsDirectRoutingAccountDetails(document.RootElement, options); + } + + internal static TeamsDirectRoutingAccountDetails DeserializeTeamsDirectRoutingAccountDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool syncEnabled = default; + bool enabled = default; + long? numberCount = default; + TeamsDirectRoutingAccountConfig configuration = default; + TeamsDirectRoutingSubdomainProvisioningStatus subdomainStatus = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("syncEnabled"u8)) + { + syncEnabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("numberCount"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + numberCount = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("configuration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + configuration = TeamsDirectRoutingAccountConfig.DeserializeTeamsDirectRoutingAccountConfig(property.Value, options); + continue; + } + if (property.NameEquals("subdomainStatus"u8)) + { + subdomainStatus = new TeamsDirectRoutingSubdomainProvisioningStatus(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsDirectRoutingAccountDetails( + syncEnabled, + enabled, + numberCount, + configuration, + subdomainStatus, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountDetails)} does not support writing '{options.Format}' format."); + } + } + + TeamsDirectRoutingAccountDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingAccountDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingAccountDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsDirectRoutingAccountDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingAccountDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.cs new file mode 100644 index 000000000000..b9fef8134b2f --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingAccountDetails.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Account details specific to Teams Direct Routing on this Account. + public partial class TeamsDirectRoutingAccountDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + public TeamsDirectRoutingAccountDetails(bool syncEnabled, bool enabled) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// The configuration for Teams Direct Routing on this account. + /// The provisioning status of the domains. + /// Keeps track of any properties unknown to the library. + internal TeamsDirectRoutingAccountDetails(bool syncEnabled, bool enabled, long? numberCount, TeamsDirectRoutingAccountConfig configuration, TeamsDirectRoutingSubdomainProvisioningStatus subdomainStatus, IDictionary serializedAdditionalRawData) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + NumberCount = numberCount; + Configuration = configuration; + SubdomainStatus = subdomainStatus; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsDirectRoutingAccountDetails() + { + } + + /// Boolean indicating if data is being provisioned through the backend service. + public bool SyncEnabled { get; set; } + /// Boolean indicating if the service is enabled on this Account. + public bool Enabled { get; set; } + /// The count of telephone numbers associated with this account that have this backend service enabled. + public long? NumberCount { get; } + /// The configuration for Teams Direct Routing on this account. + public TeamsDirectRoutingAccountConfig Configuration { get; set; } + /// The provisioning status of the domains. + public TeamsDirectRoutingSubdomainProvisioningStatus SubdomainStatus { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.Serialization.cs new file mode 100644 index 000000000000..b1a736f7e93c --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsDirectRoutingNumberDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingNumberDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsDirectRoutingNumberDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingNumberDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsDirectRoutingNumberDetails(document.RootElement, options); + } + + internal static TeamsDirectRoutingNumberDetails DeserializeTeamsDirectRoutingNumberDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsDirectRoutingNumberDetails(enabled, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingNumberDetails)} does not support writing '{options.Format}' format."); + } + } + + TeamsDirectRoutingNumberDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingNumberDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingNumberDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsDirectRoutingNumberDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingNumberDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.cs new file mode 100644 index 000000000000..ebc68a7a354d --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingNumberDetails.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Details for the Teams Direct Routing service on this Number. + public partial class TeamsDirectRoutingNumberDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + public TeamsDirectRoutingNumberDetails(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + /// Keeps track of any properties unknown to the library. + internal TeamsDirectRoutingNumberDetails(bool enabled, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsDirectRoutingNumberDetails() + { + } + + /// Boolean indicating if the service is enabled on this Number. + public bool Enabled { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainProvisioningStatus.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainProvisioningStatus.cs new file mode 100644 index 000000000000..4522670c562e --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainProvisioningStatus.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Possible values for DNS provisioning state of Teams Direct Routing domains. + public readonly partial struct TeamsDirectRoutingSubdomainProvisioningStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TeamsDirectRoutingSubdomainProvisioningStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ProvisionedValue = "provisioned"; + private const string NotProvisionedValue = "notProvisioned"; + private const string InconsistentValue = "inconsistent"; + + /// The DNS provisioning state Provisioned. + public static TeamsDirectRoutingSubdomainProvisioningStatus Provisioned { get; } = new TeamsDirectRoutingSubdomainProvisioningStatus(ProvisionedValue); + /// The DNS provisioning state Not Provisioned. + public static TeamsDirectRoutingSubdomainProvisioningStatus NotProvisioned { get; } = new TeamsDirectRoutingSubdomainProvisioningStatus(NotProvisionedValue); + /// The DNS provisioning state Inconsistent. + public static TeamsDirectRoutingSubdomainProvisioningStatus Inconsistent { get; } = new TeamsDirectRoutingSubdomainProvisioningStatus(InconsistentValue); + /// Determines if two values are the same. + public static bool operator ==(TeamsDirectRoutingSubdomainProvisioningStatus left, TeamsDirectRoutingSubdomainProvisioningStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TeamsDirectRoutingSubdomainProvisioningStatus left, TeamsDirectRoutingSubdomainProvisioningStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TeamsDirectRoutingSubdomainProvisioningStatus(string value) => new TeamsDirectRoutingSubdomainProvisioningStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TeamsDirectRoutingSubdomainProvisioningStatus other && Equals(other); + /// + public bool Equals(TeamsDirectRoutingSubdomainProvisioningStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.Serialization.cs new file mode 100644 index 000000000000..b4944d2a26ec --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsDirectRoutingSubdomainTokens : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingSubdomainTokens)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("region1Token"u8); + writer.WriteStringValue(Region1Token); + writer.WritePropertyName("region2Token"u8); + writer.WriteStringValue(Region2Token); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsDirectRoutingSubdomainTokens IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsDirectRoutingSubdomainTokens)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsDirectRoutingSubdomainTokens(document.RootElement, options); + } + + internal static TeamsDirectRoutingSubdomainTokens DeserializeTeamsDirectRoutingSubdomainTokens(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string region1Token = default; + string region2Token = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("region1Token"u8)) + { + region1Token = property.Value.GetString(); + continue; + } + if (property.NameEquals("region2Token"u8)) + { + region2Token = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsDirectRoutingSubdomainTokens(region1Token, region2Token, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingSubdomainTokens)} does not support writing '{options.Format}' format."); + } + } + + TeamsDirectRoutingSubdomainTokens IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingSubdomainTokens(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsDirectRoutingSubdomainTokens)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsDirectRoutingSubdomainTokens FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsDirectRoutingSubdomainTokens(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.cs new file mode 100644 index 000000000000..b2f2b78bd2a2 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsDirectRoutingSubdomainTokens.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// DNS TXT value for the region, as provided by the enterprise admin from their Microsoft 365 Admin Center. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. + public partial class TeamsDirectRoutingSubdomainTokens + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// DNS TXT value for the first region, as provided by the enterprise admin from their Microsoft 365 Admin Center. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. + /// DNS TXT value for the second region, as provided by the enterprise admin from their Microsoft 365 Admin Center. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. + /// or is null. + public TeamsDirectRoutingSubdomainTokens(string region1Token, string region2Token) + { + Argument.AssertNotNull(region1Token, nameof(region1Token)); + Argument.AssertNotNull(region2Token, nameof(region2Token)); + + Region1Token = region1Token; + Region2Token = region2Token; + } + + /// Initializes a new instance of . + /// DNS TXT value for the first region, as provided by the enterprise admin from their Microsoft 365 Admin Center. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. + /// DNS TXT value for the second region, as provided by the enterprise admin from their Microsoft 365 Admin Center. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. + /// Keeps track of any properties unknown to the library. + internal TeamsDirectRoutingSubdomainTokens(string region1Token, string region2Token, IDictionary serializedAdditionalRawData) + { + Region1Token = region1Token; + Region2Token = region2Token; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsDirectRoutingSubdomainTokens() + { + } + + /// DNS TXT value for the first region, as provided by the enterprise admin from their Microsoft 365 Admin Center. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. + public string Region1Token { get; set; } + /// DNS TXT value for the second region, as provided by the enterprise admin from their Microsoft 365 Admin Center. Can only contain letters, numbers, underscores and dashes. Can be up to 100 characters in length. + public string Region2Token { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.Serialization.cs new file mode 100644 index 000000000000..cc45513411bd --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsOperatorConnectAccountDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsOperatorConnectAccountDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("syncEnabled"u8); + writer.WriteBooleanValue(SyncEnabled); + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && Optional.IsDefined(NumberCount)) + { + writer.WritePropertyName("numberCount"u8); + writer.WriteNumberValue(NumberCount.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsOperatorConnectAccountDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsOperatorConnectAccountDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsOperatorConnectAccountDetails(document.RootElement, options); + } + + internal static TeamsOperatorConnectAccountDetails DeserializeTeamsOperatorConnectAccountDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool syncEnabled = default; + bool enabled = default; + long? numberCount = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("syncEnabled"u8)) + { + syncEnabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("numberCount"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + numberCount = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsOperatorConnectAccountDetails(syncEnabled, enabled, numberCount, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsOperatorConnectAccountDetails)} does not support writing '{options.Format}' format."); + } + } + + TeamsOperatorConnectAccountDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsOperatorConnectAccountDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsOperatorConnectAccountDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsOperatorConnectAccountDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsOperatorConnectAccountDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.cs new file mode 100644 index 000000000000..b367f1505d8a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectAccountDetails.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Account details specific to Teams Operator Connect on this Account. + public partial class TeamsOperatorConnectAccountDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + public TeamsOperatorConnectAccountDetails(bool syncEnabled, bool enabled) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// Keeps track of any properties unknown to the library. + internal TeamsOperatorConnectAccountDetails(bool syncEnabled, bool enabled, long? numberCount, IDictionary serializedAdditionalRawData) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + NumberCount = numberCount; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsOperatorConnectAccountDetails() + { + } + + /// Boolean indicating if data is being provisioned through the backend service. + public bool SyncEnabled { get; set; } + /// Boolean indicating if the service is enabled on this Account. + public bool Enabled { get; set; } + /// The count of telephone numbers associated with this account that have this backend service enabled. + public long? NumberCount { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.Serialization.cs new file mode 100644 index 000000000000..52d47216c8bb --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.Serialization.cs @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsOperatorConnectNumberConfig : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberConfig)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("usage"u8); + writer.WriteStringValue(Usage); + writer.WritePropertyName("choosableCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in ChoosableCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && Optional.IsCollectionDefined(AcquiredCapabilities)) + { + writer.WritePropertyName("acquiredCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in AcquiredCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && Optional.IsCollectionDefined(AvailableCapabilities)) + { + writer.WritePropertyName("availableCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in AvailableCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(AdditionalUsages)) + { + writer.WritePropertyName("additionalUsages"u8); + writer.WriteStartArray(); + foreach (var item in AdditionalUsages) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(CivicAddressId)) + { + writer.WritePropertyName("civicAddressId"u8); + writer.WriteStringValue(CivicAddressId); + } + if (Optional.IsDefined(LocationId)) + { + writer.WritePropertyName("locationId"u8); + writer.WriteStringValue(LocationId); + } + if (Optional.IsDefined(AllowTenantAddressUpdate)) + { + writer.WritePropertyName("allowTenantAddressUpdate"u8); + writer.WriteBooleanValue(AllowTenantAddressUpdate.Value); + } + if (Optional.IsDefined(DisplayedCountryCode)) + { + writer.WritePropertyName("displayedCountryCode"u8); + writer.WriteStringValue(DisplayedCountryCode); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsOperatorConnectNumberConfig IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberConfig)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsOperatorConnectNumberConfig(document.RootElement, options); + } + + internal static TeamsOperatorConnectNumberConfig DeserializeTeamsOperatorConnectNumberConfig(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string usage = default; + IList choosableCapabilities = default; + IReadOnlyList acquiredCapabilities = default; + IReadOnlyList availableCapabilities = default; + IList additionalUsages = default; + string civicAddressId = default; + string locationId = default; + bool? allowTenantAddressUpdate = default; + string displayedCountryCode = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("usage"u8)) + { + usage = property.Value.GetString(); + continue; + } + if (property.NameEquals("choosableCapabilities"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + choosableCapabilities = array; + continue; + } + if (property.NameEquals("acquiredCapabilities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + acquiredCapabilities = array; + continue; + } + if (property.NameEquals("availableCapabilities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + availableCapabilities = array; + continue; + } + if (property.NameEquals("additionalUsages"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + additionalUsages = array; + continue; + } + if (property.NameEquals("civicAddressId"u8)) + { + civicAddressId = property.Value.GetString(); + continue; + } + if (property.NameEquals("locationId"u8)) + { + locationId = property.Value.GetString(); + continue; + } + if (property.NameEquals("allowTenantAddressUpdate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + allowTenantAddressUpdate = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("displayedCountryCode"u8)) + { + displayedCountryCode = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsOperatorConnectNumberConfig( + usage, + choosableCapabilities, + acquiredCapabilities ?? new ChangeTrackingList(), + availableCapabilities ?? new ChangeTrackingList(), + additionalUsages ?? new ChangeTrackingList(), + civicAddressId, + locationId, + allowTenantAddressUpdate, + displayedCountryCode, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberConfig)} does not support writing '{options.Format}' format."); + } + } + + TeamsOperatorConnectNumberConfig IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsOperatorConnectNumberConfig(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberConfig)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsOperatorConnectNumberConfig FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsOperatorConnectNumberConfig(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.cs new file mode 100644 index 000000000000..5029e46ddeea --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberConfig.cs @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Telephone number configuration for Teams Operator Connect telephone numbers. + public partial class TeamsOperatorConnectNumberConfig + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The usage for this telephone number. + /// The choosable capabilities for this telephone number. + /// or is null. + public TeamsOperatorConnectNumberConfig(string usage, IEnumerable choosableCapabilities) + { + Argument.AssertNotNull(usage, nameof(usage)); + Argument.AssertNotNull(choosableCapabilities, nameof(choosableCapabilities)); + + Usage = usage; + ChoosableCapabilities = choosableCapabilities.ToList(); + AcquiredCapabilities = new ChangeTrackingList(); + AvailableCapabilities = new ChangeTrackingList(); + AdditionalUsages = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The usage for this telephone number. + /// The choosable capabilities for this telephone number. + /// The acquired capabilities for this telephone number. + /// The available capabilities for this telephone number. + /// The additional usages for this telephone number. + /// The ID of the civic address to be used as the emergency address for this telephone number. + /// The ID of the location to be used as the emergency address for this telephone number. + /// If the enterprise is allowed to update the address for this telephone number. + /// The country code to be displayed with this telephone number. + /// Keeps track of any properties unknown to the library. + internal TeamsOperatorConnectNumberConfig(string usage, IList choosableCapabilities, IReadOnlyList acquiredCapabilities, IReadOnlyList availableCapabilities, IList additionalUsages, string civicAddressId, string locationId, bool? allowTenantAddressUpdate, string displayedCountryCode, IDictionary serializedAdditionalRawData) + { + Usage = usage; + ChoosableCapabilities = choosableCapabilities; + AcquiredCapabilities = acquiredCapabilities; + AvailableCapabilities = availableCapabilities; + AdditionalUsages = additionalUsages; + CivicAddressId = civicAddressId; + LocationId = locationId; + AllowTenantAddressUpdate = allowTenantAddressUpdate; + DisplayedCountryCode = displayedCountryCode; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsOperatorConnectNumberConfig() + { + } + + /// The usage for this telephone number. + public string Usage { get; set; } + /// The choosable capabilities for this telephone number. + public IList ChoosableCapabilities { get; } + /// The acquired capabilities for this telephone number. + public IReadOnlyList AcquiredCapabilities { get; } + /// The available capabilities for this telephone number. + public IReadOnlyList AvailableCapabilities { get; } + /// The additional usages for this telephone number. + public IList AdditionalUsages { get; } + /// The ID of the civic address to be used as the emergency address for this telephone number. + public string CivicAddressId { get; set; } + /// The ID of the location to be used as the emergency address for this telephone number. + public string LocationId { get; set; } + /// If the enterprise is allowed to update the address for this telephone number. + public bool? AllowTenantAddressUpdate { get; set; } + /// The country code to be displayed with this telephone number. + public string DisplayedCountryCode { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.Serialization.cs new file mode 100644 index 000000000000..bd990a73cbdd --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.Serialization.cs @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsOperatorConnectNumberDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (Optional.IsDefined(AssignmentStatus)) + { + writer.WritePropertyName("assignmentStatus"u8); + writer.WriteStringValue(AssignmentStatus.Value.ToString()); + } + if (Optional.IsDefined(Configuration)) + { + writer.WritePropertyName("configuration"u8); + writer.WriteObjectValue(Configuration, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsOperatorConnectNumberDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsOperatorConnectNumberDetails(document.RootElement, options); + } + + internal static TeamsOperatorConnectNumberDetails DeserializeTeamsOperatorConnectNumberDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + TelephoneNumberAssignmentStatus? assignmentStatus = default; + TeamsOperatorConnectNumberConfig configuration = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("assignmentStatus"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + assignmentStatus = new TelephoneNumberAssignmentStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("configuration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + configuration = TeamsOperatorConnectNumberConfig.DeserializeTeamsOperatorConnectNumberConfig(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsOperatorConnectNumberDetails(enabled, assignmentStatus, configuration, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberDetails)} does not support writing '{options.Format}' format."); + } + } + + TeamsOperatorConnectNumberDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsOperatorConnectNumberDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsOperatorConnectNumberDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsOperatorConnectNumberDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsOperatorConnectNumberDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.cs new file mode 100644 index 000000000000..052ff99c39f8 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsOperatorConnectNumberDetails.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Details for the Teams Operator Connect service on this Number. + public partial class TeamsOperatorConnectNumberDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + public TeamsOperatorConnectNumberDetails(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + /// The assignment status of this Number. + /// The configuration for Teams Operator Connect on this number. + /// Keeps track of any properties unknown to the library. + internal TeamsOperatorConnectNumberDetails(bool enabled, TelephoneNumberAssignmentStatus? assignmentStatus, TeamsOperatorConnectNumberConfig configuration, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + AssignmentStatus = assignmentStatus; + Configuration = configuration; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsOperatorConnectNumberDetails() + { + } + + /// Boolean indicating if the service is enabled on this Number. + public bool Enabled { get; set; } + /// The assignment status of this Number. + public TelephoneNumberAssignmentStatus? AssignmentStatus { get; set; } + /// The configuration for Teams Operator Connect on this number. + public TeamsOperatorConnectNumberConfig Configuration { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.Serialization.cs new file mode 100644 index 000000000000..a23ece304e52 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsPhoneMobileAccountDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsPhoneMobileAccountDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("syncEnabled"u8); + writer.WriteBooleanValue(SyncEnabled); + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && Optional.IsDefined(NumberCount)) + { + writer.WritePropertyName("numberCount"u8); + writer.WriteNumberValue(NumberCount.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsPhoneMobileAccountDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsPhoneMobileAccountDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsPhoneMobileAccountDetails(document.RootElement, options); + } + + internal static TeamsPhoneMobileAccountDetails DeserializeTeamsPhoneMobileAccountDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool syncEnabled = default; + bool enabled = default; + long? numberCount = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("syncEnabled"u8)) + { + syncEnabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("numberCount"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + numberCount = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsPhoneMobileAccountDetails(syncEnabled, enabled, numberCount, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsPhoneMobileAccountDetails)} does not support writing '{options.Format}' format."); + } + } + + TeamsPhoneMobileAccountDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsPhoneMobileAccountDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsPhoneMobileAccountDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsPhoneMobileAccountDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsPhoneMobileAccountDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.cs new file mode 100644 index 000000000000..d1896867d8c2 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileAccountDetails.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Account details specific to Teams Phone Mobile. + public partial class TeamsPhoneMobileAccountDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + public TeamsPhoneMobileAccountDetails(bool syncEnabled, bool enabled) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// Keeps track of any properties unknown to the library. + internal TeamsPhoneMobileAccountDetails(bool syncEnabled, bool enabled, long? numberCount, IDictionary serializedAdditionalRawData) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + NumberCount = numberCount; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsPhoneMobileAccountDetails() + { + } + + /// Boolean indicating if data is being provisioned through the backend service. + public bool SyncEnabled { get; set; } + /// Boolean indicating if the service is enabled on this Account. + public bool Enabled { get; set; } + /// The count of telephone numbers associated with this account that have this backend service enabled. + public long? NumberCount { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.Serialization.cs new file mode 100644 index 000000000000..ba9ca9d73d04 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.Serialization.cs @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsPhoneMobileNumberConfig : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberConfig)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("usage"u8); + writer.WriteStringValue(Usage); + writer.WritePropertyName("choosableCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in ChoosableCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && Optional.IsCollectionDefined(AcquiredCapabilities)) + { + writer.WritePropertyName("acquiredCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in AcquiredCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && Optional.IsCollectionDefined(AvailableCapabilities)) + { + writer.WritePropertyName("availableCapabilities"u8); + writer.WriteStartArray(); + foreach (var item in AvailableCapabilities) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(AdditionalUsages)) + { + writer.WritePropertyName("additionalUsages"u8); + writer.WriteStartArray(); + foreach (var item in AdditionalUsages) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(CivicAddressId)) + { + writer.WritePropertyName("civicAddressId"u8); + writer.WriteStringValue(CivicAddressId); + } + if (Optional.IsDefined(LocationId)) + { + writer.WritePropertyName("locationId"u8); + writer.WriteStringValue(LocationId); + } + if (Optional.IsDefined(AllowTenantAddressUpdate)) + { + writer.WritePropertyName("allowTenantAddressUpdate"u8); + writer.WriteBooleanValue(AllowTenantAddressUpdate.Value); + } + if (Optional.IsDefined(DisplayedCountryCode)) + { + writer.WritePropertyName("displayedCountryCode"u8); + writer.WriteStringValue(DisplayedCountryCode); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsPhoneMobileNumberConfig IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberConfig)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsPhoneMobileNumberConfig(document.RootElement, options); + } + + internal static TeamsPhoneMobileNumberConfig DeserializeTeamsPhoneMobileNumberConfig(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string usage = default; + IList choosableCapabilities = default; + IReadOnlyList acquiredCapabilities = default; + IReadOnlyList availableCapabilities = default; + IList additionalUsages = default; + string civicAddressId = default; + string locationId = default; + bool? allowTenantAddressUpdate = default; + string displayedCountryCode = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("usage"u8)) + { + usage = property.Value.GetString(); + continue; + } + if (property.NameEquals("choosableCapabilities"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + choosableCapabilities = array; + continue; + } + if (property.NameEquals("acquiredCapabilities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + acquiredCapabilities = array; + continue; + } + if (property.NameEquals("availableCapabilities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + availableCapabilities = array; + continue; + } + if (property.NameEquals("additionalUsages"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + additionalUsages = array; + continue; + } + if (property.NameEquals("civicAddressId"u8)) + { + civicAddressId = property.Value.GetString(); + continue; + } + if (property.NameEquals("locationId"u8)) + { + locationId = property.Value.GetString(); + continue; + } + if (property.NameEquals("allowTenantAddressUpdate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + allowTenantAddressUpdate = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("displayedCountryCode"u8)) + { + displayedCountryCode = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsPhoneMobileNumberConfig( + usage, + choosableCapabilities, + acquiredCapabilities ?? new ChangeTrackingList(), + availableCapabilities ?? new ChangeTrackingList(), + additionalUsages ?? new ChangeTrackingList(), + civicAddressId, + locationId, + allowTenantAddressUpdate, + displayedCountryCode, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberConfig)} does not support writing '{options.Format}' format."); + } + } + + TeamsPhoneMobileNumberConfig IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsPhoneMobileNumberConfig(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberConfig)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsPhoneMobileNumberConfig FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsPhoneMobileNumberConfig(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.cs new file mode 100644 index 000000000000..f735d91ff1d0 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberConfig.cs @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Telephone number configuration for Teams Phone Mobile telephone numbers. + public partial class TeamsPhoneMobileNumberConfig + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The usage for this telephone number. + /// The choosable capabilities for this telephone number. + /// or is null. + public TeamsPhoneMobileNumberConfig(string usage, IEnumerable choosableCapabilities) + { + Argument.AssertNotNull(usage, nameof(usage)); + Argument.AssertNotNull(choosableCapabilities, nameof(choosableCapabilities)); + + Usage = usage; + ChoosableCapabilities = choosableCapabilities.ToList(); + AcquiredCapabilities = new ChangeTrackingList(); + AvailableCapabilities = new ChangeTrackingList(); + AdditionalUsages = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The usage for this telephone number. + /// The choosable capabilities for this telephone number. + /// The acquired capabilities for this telephone number. + /// The available capabilities for this telephone number. + /// The additional usages for this telephone number. + /// The ID of the civic address to be used as the emergency address for this telephone number. + /// The ID of the location to be used as the emergency address for this telephone number. + /// If the enterprise is allowed to update the address for this telephone number. + /// The country code to be displayed with this telephone number. + /// Keeps track of any properties unknown to the library. + internal TeamsPhoneMobileNumberConfig(string usage, IList choosableCapabilities, IReadOnlyList acquiredCapabilities, IReadOnlyList availableCapabilities, IList additionalUsages, string civicAddressId, string locationId, bool? allowTenantAddressUpdate, string displayedCountryCode, IDictionary serializedAdditionalRawData) + { + Usage = usage; + ChoosableCapabilities = choosableCapabilities; + AcquiredCapabilities = acquiredCapabilities; + AvailableCapabilities = availableCapabilities; + AdditionalUsages = additionalUsages; + CivicAddressId = civicAddressId; + LocationId = locationId; + AllowTenantAddressUpdate = allowTenantAddressUpdate; + DisplayedCountryCode = displayedCountryCode; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsPhoneMobileNumberConfig() + { + } + + /// The usage for this telephone number. + public string Usage { get; set; } + /// The choosable capabilities for this telephone number. + public IList ChoosableCapabilities { get; } + /// The acquired capabilities for this telephone number. + public IReadOnlyList AcquiredCapabilities { get; } + /// The available capabilities for this telephone number. + public IReadOnlyList AvailableCapabilities { get; } + /// The additional usages for this telephone number. + public IList AdditionalUsages { get; } + /// The ID of the civic address to be used as the emergency address for this telephone number. + public string CivicAddressId { get; set; } + /// The ID of the location to be used as the emergency address for this telephone number. + public string LocationId { get; set; } + /// If the enterprise is allowed to update the address for this telephone number. + public bool? AllowTenantAddressUpdate { get; set; } + /// The country code to be displayed with this telephone number. + public string DisplayedCountryCode { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.Serialization.cs new file mode 100644 index 000000000000..a15007755784 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.Serialization.cs @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class TeamsPhoneMobileNumberDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (Optional.IsDefined(AssignmentStatus)) + { + writer.WritePropertyName("assignmentStatus"u8); + writer.WriteStringValue(AssignmentStatus.Value.ToString()); + } + if (Optional.IsDefined(Configuration)) + { + writer.WritePropertyName("configuration"u8); + writer.WriteObjectValue(Configuration, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + TeamsPhoneMobileNumberDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTeamsPhoneMobileNumberDetails(document.RootElement, options); + } + + internal static TeamsPhoneMobileNumberDetails DeserializeTeamsPhoneMobileNumberDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + TelephoneNumberAssignmentStatus? assignmentStatus = default; + TeamsPhoneMobileNumberConfig configuration = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("assignmentStatus"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + assignmentStatus = new TelephoneNumberAssignmentStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("configuration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + configuration = TeamsPhoneMobileNumberConfig.DeserializeTeamsPhoneMobileNumberConfig(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new TeamsPhoneMobileNumberDetails(enabled, assignmentStatus, configuration, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberDetails)} does not support writing '{options.Format}' format."); + } + } + + TeamsPhoneMobileNumberDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsPhoneMobileNumberDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(TeamsPhoneMobileNumberDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static TeamsPhoneMobileNumberDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTeamsPhoneMobileNumberDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.cs new file mode 100644 index 000000000000..e231b281d666 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsPhoneMobileNumberDetails.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Details for the Teams Phone Mobile service on this Number. + public partial class TeamsPhoneMobileNumberDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + public TeamsPhoneMobileNumberDetails(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + /// The assignment status of this Number. + /// The configuration for Teams Phone Mobile on this number. + /// Keeps track of any properties unknown to the library. + internal TeamsPhoneMobileNumberDetails(bool enabled, TelephoneNumberAssignmentStatus? assignmentStatus, TeamsPhoneMobileNumberConfig configuration, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + AssignmentStatus = assignmentStatus; + Configuration = configuration; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TeamsPhoneMobileNumberDetails() + { + } + + /// Boolean indicating if the service is enabled on this Number. + public bool Enabled { get; set; } + /// The assignment status of this Number. + public TelephoneNumberAssignmentStatus? AssignmentStatus { get; set; } + /// The configuration for Teams Phone Mobile on this number. + public TeamsPhoneMobileNumberConfig Configuration { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsRequestsForInformation.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsRequestsForInformation.cs new file mode 100644 index 000000000000..98457816e1ec --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TeamsRequestsForInformation.cs @@ -0,0 +1,447 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Microsoft.VoiceServices.Provisioning +{ + // Data plane generated sub-client. + /// The TeamsRequestsForInformation sub-client. + public partial class TeamsRequestsForInformation + { + private static readonly string[] AuthorizationScopes = new string[] { "https://func-voiceservice-rp-prod-eastuseuap.azurewebsites.net/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of TeamsRequestsForInformation for mocking. + protected TeamsRequestsForInformation() + { + } + + /// Initializes a new instance of TeamsRequestsForInformation. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// Service host. + /// The API version to use for this operation. + internal TeamsRequestsForInformation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get Request for Information. + /// The Teams tenant ID which generated this Request for Information. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get details of a specific Request for Information using its ID. + /// + public virtual async Task> GetRequestForInformationAsync(string tenantId, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(tenantId, nameof(tenantId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetRequestForInformationAsync(tenantId, requestConditions, context).ConfigureAwait(false); + return Response.FromValue(RequestForInformationResource.FromResponse(response), response); + } + + /// Get Request for Information. + /// The Teams tenant ID which generated this Request for Information. + /// The content to send as the request conditions of the request. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Get details of a specific Request for Information using its ID. + /// + public virtual Response GetRequestForInformation(string tenantId, RequestConditions requestConditions = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(tenantId, nameof(tenantId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetRequestForInformation(tenantId, requestConditions, context); + return Response.FromValue(RequestForInformationResource.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get Request for Information. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The Teams tenant ID which generated this Request for Information. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetRequestForInformationAsync(string tenantId, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(tenantId, nameof(tenantId)); + + using var scope = ClientDiagnostics.CreateScope("TeamsRequestsForInformation.GetRequestForInformation"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRequestForInformationRequest(tenantId, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get Request for Information. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The Teams tenant ID which generated this Request for Information. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetRequestForInformation(string tenantId, RequestConditions requestConditions, RequestContext context) + { + Argument.AssertNotNullOrEmpty(tenantId, nameof(tenantId)); + + using var scope = ClientDiagnostics.CreateScope("TeamsRequestsForInformation.GetRequestForInformation"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRequestForInformationRequest(tenantId, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create or update Request for Information. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The Teams tenant ID which generated this Request for Information. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task CreateOrUpdateRequestForInformationAsync(string tenantId, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(tenantId, nameof(tenantId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TeamsRequestsForInformation.CreateOrUpdateRequestForInformation"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateRequestForInformationRequest(tenantId, content, requestConditions, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Create or update Request for Information. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The Teams tenant ID which generated this Request for Information. + /// The content to send as the body of the request. + /// The content to send as the request conditions of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response CreateOrUpdateRequestForInformation(string tenantId, RequestContent content, RequestConditions requestConditions = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(tenantId, nameof(tenantId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("TeamsRequestsForInformation.CreateOrUpdateRequestForInformation"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateOrUpdateRequestForInformationRequest(tenantId, content, requestConditions, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get list of Requests for Information. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// Get list of Requests for Information with details. + /// + public virtual AsyncPageable GetRequestForInformationResourcesAsync(int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRequestForInformationResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRequestForInformationResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => RequestForInformationResource.DeserializeRequestForInformationResource(e), ClientDiagnostics, _pipeline, "TeamsRequestsForInformation.GetRequestForInformationResources", "value", "nextLink", maxpagesize, context); + } + + /// Get list of Requests for Information. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// Get list of Requests for Information with details. + /// + public virtual Pageable GetRequestForInformationResources(int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRequestForInformationResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRequestForInformationResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => RequestForInformationResource.DeserializeRequestForInformationResource(e), ClientDiagnostics, _pipeline, "TeamsRequestsForInformation.GetRequestForInformationResources", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get list of Requests for Information + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetRequestForInformationResourcesAsync(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRequestForInformationResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRequestForInformationResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "TeamsRequestsForInformation.GetRequestForInformationResources", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] Get list of Requests for Information + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetRequestForInformationResources(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetRequestForInformationResourcesRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetRequestForInformationResourcesNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "TeamsRequestsForInformation.GetRequestForInformationResources", "value", "nextLink", maxpagesize, context); + } + + internal HttpMessage CreateGetRequestForInformationResourcesRequest(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/teamsRequestsForInformation", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (countRecords != null) + { + uri.AppendQuery("countRecords", countRecords.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetRequestForInformationRequest(string tenantId, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/teamsRequestsForInformation/", false); + uri.AppendPath(tenantId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + return message; + } + + internal HttpMessage CreateCreateOrUpdateRequestForInformationRequest(string tenantId, RequestContent content, RequestConditions requestConditions, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200201); + var request = message.Request; + request.Method = RequestMethod.Patch; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/teamsRequestsForInformation/", false); + uri.AppendPath(tenantId, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Repeatability-Request-ID", Guid.NewGuid()); + request.Headers.Add("Repeatability-First-Sent", DateTimeOffset.Now, "R"); + if (requestConditions != null) + { + request.Headers.Add(requestConditions, "R"); + } + request.Headers.Add("Content-Type", "application/merge-patch+json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetRequestForInformationResourcesNextPageRequest(string nextLink, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier200201; + private static ResponseClassifier ResponseClassifier200201 => _responseClassifier200201 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 201 }); + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TelephoneNumberAssignmentStatus.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TelephoneNumberAssignmentStatus.cs new file mode 100644 index 000000000000..31c212154bd5 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/TelephoneNumberAssignmentStatus.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Indicates whether a number is assigned to a user. + public readonly partial struct TelephoneNumberAssignmentStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TelephoneNumberAssignmentStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AssignedValue = "assigned"; + private const string UnassignedValue = "unassigned"; + + /// The telephone number is assigned to a user. + public static TelephoneNumberAssignmentStatus Assigned { get; } = new TelephoneNumberAssignmentStatus(AssignedValue); + /// The telephone number is not assigned to a user. + public static TelephoneNumberAssignmentStatus Unassigned { get; } = new TelephoneNumberAssignmentStatus(UnassignedValue); + /// Determines if two values are the same. + public static bool operator ==(TelephoneNumberAssignmentStatus left, TelephoneNumberAssignmentStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TelephoneNumberAssignmentStatus left, TelephoneNumberAssignmentStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TelephoneNumberAssignmentStatus(string value) => new TelephoneNumberAssignmentStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TelephoneNumberAssignmentStatus other && Equals(other); + /// + public bool Equals(TelephoneNumberAssignmentStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ValidationStatus.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ValidationStatus.cs new file mode 100644 index 000000000000..de36d3c44ff4 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ValidationStatus.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// The possible validation status of Teams Civic Addresses. + public readonly partial struct ValidationStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ValidationStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NotValidatedValue = "notValidated"; + private const string ValidatedValue = "validated"; + + /// The civic address is not validated. + public static ValidationStatus NotValidated { get; } = new ValidationStatus(NotValidatedValue); + /// The civic address is validated. + public static ValidationStatus Validated { get; } = new ValidationStatus(ValidatedValue); + /// Determines if two values are the same. + public static bool operator ==(ValidationStatus left, ValidationStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ValidationStatus left, ValidationStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ValidationStatus(string value) => new ValidationStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ValidationStatus other && Equals(other); + /// + public bool Equals(ValidationStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClient.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClient.cs new file mode 100644 index 000000000000..5b7bfd51e4bd --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClient.cs @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using Autorest.CSharp.Core; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Microsoft.VoiceServices.Provisioning +{ + // Data plane generated client. + /// The VoiceServices service client. + public partial class VoiceServicesClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://func-voiceservice-rp-prod-eastuseuap.azurewebsites.net/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of VoiceServicesClient for mocking. + protected VoiceServicesClient() + { + } + + /// Initializes a new instance of VoiceServicesClient. + /// Service host. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public VoiceServicesClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new VoiceServicesClientOptions()) + { + } + + /// Initializes a new instance of VoiceServicesClient. + /// Service host. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public VoiceServicesClient(Uri endpoint, TokenCredential credential, VoiceServicesClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new VoiceServicesClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// List all the Numbers associated with this Communications Gateway. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// + public virtual AsyncPageable GetNumbersAsync(int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => NumberResource.DeserializeNumberResource(e), ClientDiagnostics, _pipeline, "VoiceServicesClient.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + /// List all the Numbers associated with this Communications Gateway. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The cancellation token to use. + /// + public virtual Pageable GetNumbers(int? maxCount = null, int? skip = null, int? maxpagesize = null, string filter = null, bool? countRecords = null, CancellationToken cancellationToken = default) + { + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => NumberResource.DeserializeNumberResource(e), ClientDiagnostics, _pipeline, "VoiceServicesClient.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all the Numbers associated with this Communications Gateway. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetNumbersAsync(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "VoiceServicesClient.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + /// + /// [Protocol Method] List all the Numbers associated with this Communications Gateway. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Filter the result list using the given expression. + /// Whether to return a count of the total number of records available for this request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetNumbers(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetNumbersRequest(maxCount, skip, pageSizeHint, filter, countRecords, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetNumbersNextPageRequest(nextLink, maxCount, skip, pageSizeHint, filter, countRecords, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "VoiceServicesClient.GetNumbers", "value", "nextLink", maxpagesize, context); + } + + private Accounts _cachedAccounts; + private TeamsRequestsForInformation _cachedTeamsRequestsForInformation; + + /// Initializes a new instance of Accounts. + public virtual Accounts GetAccountsClient() + { + return Volatile.Read(ref _cachedAccounts) ?? Interlocked.CompareExchange(ref _cachedAccounts, new Accounts(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, _apiVersion), null) ?? _cachedAccounts; + } + + /// Initializes a new instance of TeamsRequestsForInformation. + public virtual TeamsRequestsForInformation GetTeamsRequestsForInformationClient() + { + return Volatile.Read(ref _cachedTeamsRequestsForInformation) ?? Interlocked.CompareExchange(ref _cachedTeamsRequestsForInformation, new TeamsRequestsForInformation(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, _apiVersion), null) ?? _cachedTeamsRequestsForInformation; + } + + internal HttpMessage CreateGetNumbersRequest(int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/numbers", false); + uri.AppendQuery("api-version", _apiVersion, true); + if (maxCount != null) + { + uri.AppendQuery("top", maxCount.Value, true); + } + if (skip != null) + { + uri.AppendQuery("skip", skip.Value, true); + } + if (maxpagesize != null) + { + uri.AppendQuery("maxpagesize", maxpagesize.Value, true); + } + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (countRecords != null) + { + uri.AppendQuery("countRecords", countRecords.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetNumbersNextPageRequest(string nextLink, int? maxCount, int? skip, int? maxpagesize, string filter, bool? countRecords, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClientOptions.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClientOptions.cs new file mode 100644 index 000000000000..3de5d3b1a424 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/VoiceServicesClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Client options for VoiceServicesClient. + public partial class VoiceServicesClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2024_02_29_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2024-02-29-preview". + V2024_02_29_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of VoiceServicesClientOptions. + public VoiceServicesClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2024_02_29_Preview => "2024-02-29-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.Serialization.cs new file mode 100644 index 000000000000..e603f0848603 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class ZoomPhoneCloudPeeringAccountDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringAccountDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("syncEnabled"u8); + writer.WriteBooleanValue(SyncEnabled); + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && Optional.IsDefined(NumberCount)) + { + writer.WritePropertyName("numberCount"u8); + writer.WriteNumberValue(NumberCount.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ZoomPhoneCloudPeeringAccountDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringAccountDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeZoomPhoneCloudPeeringAccountDetails(document.RootElement, options); + } + + internal static ZoomPhoneCloudPeeringAccountDetails DeserializeZoomPhoneCloudPeeringAccountDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool syncEnabled = default; + bool enabled = default; + long? numberCount = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("syncEnabled"u8)) + { + syncEnabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("numberCount"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + numberCount = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ZoomPhoneCloudPeeringAccountDetails(syncEnabled, enabled, numberCount, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringAccountDetails)} does not support writing '{options.Format}' format."); + } + } + + ZoomPhoneCloudPeeringAccountDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeZoomPhoneCloudPeeringAccountDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringAccountDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ZoomPhoneCloudPeeringAccountDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeZoomPhoneCloudPeeringAccountDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.cs new file mode 100644 index 000000000000..2241ffb21ba7 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringAccountDetails.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Account details specific to Zoom Phone Cloud Peering. + public partial class ZoomPhoneCloudPeeringAccountDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + public ZoomPhoneCloudPeeringAccountDetails(bool syncEnabled, bool enabled) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if data is being provisioned through the backend service. + /// Boolean indicating if the service is enabled on this Account. + /// The count of telephone numbers associated with this account that have this backend service enabled. + /// Keeps track of any properties unknown to the library. + internal ZoomPhoneCloudPeeringAccountDetails(bool syncEnabled, bool enabled, long? numberCount, IDictionary serializedAdditionalRawData) + { + SyncEnabled = syncEnabled; + Enabled = enabled; + NumberCount = numberCount; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ZoomPhoneCloudPeeringAccountDetails() + { + } + + /// Boolean indicating if data is being provisioned through the backend service. + public bool SyncEnabled { get; set; } + /// Boolean indicating if the service is enabled on this Account. + public bool Enabled { get; set; } + /// The count of telephone numbers associated with this account that have this backend service enabled. + public long? NumberCount { get; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.Serialization.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.Serialization.cs new file mode 100644 index 000000000000..e997c2494758 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.VoiceServices.Provisioning +{ + public partial class ZoomPhoneCloudPeeringNumberDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringNumberDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ZoomPhoneCloudPeeringNumberDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringNumberDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeZoomPhoneCloudPeeringNumberDetails(document.RootElement, options); + } + + internal static ZoomPhoneCloudPeeringNumberDetails DeserializeZoomPhoneCloudPeeringNumberDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ZoomPhoneCloudPeeringNumberDetails(enabled, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringNumberDetails)} does not support writing '{options.Format}' format."); + } + } + + ZoomPhoneCloudPeeringNumberDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeZoomPhoneCloudPeeringNumberDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ZoomPhoneCloudPeeringNumberDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ZoomPhoneCloudPeeringNumberDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeZoomPhoneCloudPeeringNumberDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.cs new file mode 100644 index 000000000000..eafd400491c4 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Generated/ZoomPhoneCloudPeeringNumberDetails.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.VoiceServices.Provisioning +{ + /// Details for the Zoom Phone Cloud Peering service on this Number. + public partial class ZoomPhoneCloudPeeringNumberDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + public ZoomPhoneCloudPeeringNumberDetails(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Boolean indicating if the service is enabled on this Number. + /// Keeps track of any properties unknown to the library. + internal ZoomPhoneCloudPeeringNumberDetails(bool enabled, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ZoomPhoneCloudPeeringNumberDetails() + { + } + + /// Boolean indicating if the service is enabled on this Number. + public bool Enabled { get; set; } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Microsoft.VoiceServices.Provisioning.csproj b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Microsoft.VoiceServices.Provisioning.csproj new file mode 100644 index 000000000000..b143463061ac --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Microsoft.VoiceServices.Provisioning.csproj @@ -0,0 +1,19 @@ + + + This is the Microsoft.VoiceServices.Provisioning client library for developing .NET applications with rich experience. + Azure SDK Code Generation Microsoft.VoiceServices.Provisioning for Azure Data Plane + 1.0.0-beta.1 + Microsoft.VoiceServices.Provisioning + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Properties/AssemblyInfo.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..d37c9d4475c3 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/src/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Microsoft.VoiceServices.Provisioning.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_Accounts.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_Accounts.cs new file mode 100644 index 000000000000..962b59605f2b --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_Accounts.cs @@ -0,0 +1,988 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Microsoft.VoiceServices.Provisioning.Samples +{ + public partial class Samples_Accounts + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_AccountResource_GetAccountResource_GetAccount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetAccountResource("contoso", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_AccountResource_GetAccountResource_GetAccount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetAccountResourceAsync("contoso", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_AccountResource_GetAccountResource_GetAccount_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetAccountResource("contoso"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_AccountResource_GetAccountResource_GetAccount_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetAccountResourceAsync("contoso"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_AccountResource_CreateOrReplace_CreateOrReplaceAccount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + name = "contoso", + correlationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + serviceDetails = new + { + teamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + teamsOperatorConnect = new + { + enabled = true, + syncEnabled = true, + }, + }, + }); + Response response = client.CreateOrReplace("contoso", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_AccountResource_CreateOrReplace_CreateOrReplaceAccount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + name = "contoso", + correlationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + serviceDetails = new + { + teamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + teamsOperatorConnect = new + { + enabled = true, + syncEnabled = true, + }, + }, + }); + Response response = await client.CreateOrReplaceAsync("contoso", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_AccountResource_CreateOrReplace_CreateOrReplaceAccount_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + AccountResource resource = new AccountResource("contoso") + { + CorrelationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + ServiceDetails = new AccountServiceDetails + { + TeamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + TeamsOperatorConnect = new TeamsOperatorConnectAccountDetails(true, true), + }, + }; + Response response = client.CreateOrReplace("contoso", resource); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_AccountResource_CreateOrReplace_CreateOrReplaceAccount_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + AccountResource resource = new AccountResource("contoso") + { + CorrelationId = "c7aa0070-3956-11eb-8d59-4d9d2e7a4a8d", + ServiceDetails = new AccountServiceDetails + { + TeamsTenantId = "a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", + TeamsOperatorConnect = new TeamsOperatorConnectAccountDetails(true, true), + }, + }; + Response response = await client.CreateOrReplaceAsync("contoso", resource); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_AccountResource_Delete_DeleteAccount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.Delete("contoso"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_AccountResource_Delete_DeleteAccount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.DeleteAsync("contoso"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_CreateOrUpdateNumbers_CreateOrUpdateNumbers() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + numbers = new object[] + { +new +{ +telephoneNumber = "+15105850321", +accountName = "contoso", +serviceDetails = new +{ +teamsOperatorConnect = new +{ +enabled = true, +assignmentStatus = "assigned", +configuration = new +{ +usage = "CallingUserAssignment", +choosableCapabilities = new object[] +{ +"InboundCalling" +}, +}, +}, +}, +configuration = new +{ +customSipHeader = "contoso-commsgw", +}, +} + }, + }); + Response response = client.CreateOrUpdateNumbers("contoso", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("serviceDetails").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_CreateOrUpdateNumbers_CreateOrUpdateNumbers_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + numbers = new object[] + { +new +{ +telephoneNumber = "+15105850321", +accountName = "contoso", +serviceDetails = new +{ +teamsOperatorConnect = new +{ +enabled = true, +assignmentStatus = "assigned", +configuration = new +{ +usage = "CallingUserAssignment", +choosableCapabilities = new object[] +{ +"InboundCalling" +}, +}, +}, +}, +configuration = new +{ +customSipHeader = "contoso-commsgw", +}, +} + }, + }); + Response response = await client.CreateOrUpdateNumbersAsync("contoso", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("numbers")[0].GetProperty("serviceDetails").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_CreateOrUpdateNumbers_CreateOrUpdateNumbers_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + BatchNumbers body = new BatchNumbers(new NumberResource[] + { +new NumberResource("+15105850321", "contoso", new NumberServiceDetails +{ +TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) +{ +AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, +Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[]{"InboundCalling"}), +}, +}) +{ +Configuration = new NumberConfiguration +{ +CustomSipHeader = "contoso-commsgw", +}, +} + }); + Response response = client.CreateOrUpdateNumbers("contoso", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_CreateOrUpdateNumbers_CreateOrUpdateNumbers_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + BatchNumbers body = new BatchNumbers(new NumberResource[] + { +new NumberResource("+15105850321", "contoso", new NumberServiceDetails +{ +TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) +{ +AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, +Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[]{"InboundCalling"}), +}, +}) +{ +Configuration = new NumberConfiguration +{ +CustomSipHeader = "contoso-commsgw", +}, +} + }); + Response response = await client.CreateOrUpdateNumbersAsync("contoso", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_DeleteNumbers_DeleteBatchesOfNumbers() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + numbers = new object[] + { +new +{ +telephoneNumber = "+15105850321", +} + }, + }); + Response response = client.DeleteNumbers("contoso", content); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_DeleteNumbers_DeleteBatchesOfNumbers_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + numbers = new object[] + { +new +{ +telephoneNumber = "+15105850321", +} + }, + }); + Response response = await client.DeleteNumbersAsync("contoso", content); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_DeleteNumbers_DeleteBatchesOfNumbers_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + BatchNumbersDelete body = new BatchNumbersDelete(new NumberIdentifier[] + { +new NumberIdentifier("+15105850321") + }); + Response response = client.DeleteNumbers("contoso", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_DeleteNumbers_DeleteBatchesOfNumbers_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + BatchNumbersDelete body = new BatchNumbersDelete(new NumberIdentifier[] + { +new NumberIdentifier("+15105850321") + }); + Response response = await client.DeleteNumbersAsync("contoso", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_GetNumber_GetANumberFromAnAccount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetNumber("contoso", "+15105850321", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_GetNumber_GetANumberFromAnAccount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetNumberAsync("contoso", "+15105850321", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_GetNumber_GetANumberFromAnAccount_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetNumber("contoso", "+15105850321"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_GetNumber_GetANumberFromAnAccount_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetNumberAsync("contoso", "+15105850321"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_CreateOrReplaceNumber_CreateOrReplaceANumber() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + telephoneNumber = "+15105850321", + accountName = "contoso", + serviceDetails = new + { + teamsOperatorConnect = new + { + enabled = true, + assignmentStatus = "assigned", + configuration = new + { + usage = "CallingUserAssignment", + choosableCapabilities = new object[] + { +"InboundCalling" + }, + }, + }, + }, + configuration = new + { + customSipHeader = "contoso-commsgw", + }, + }); + Response response = client.CreateOrReplaceNumber("contoso", "+15105850321", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_CreateOrReplaceNumber_CreateOrReplaceANumber_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + telephoneNumber = "+15105850321", + accountName = "contoso", + serviceDetails = new + { + teamsOperatorConnect = new + { + enabled = true, + assignmentStatus = "assigned", + configuration = new + { + usage = "CallingUserAssignment", + choosableCapabilities = new object[] + { +"InboundCalling" + }, + }, + }, + }, + configuration = new + { + customSipHeader = "contoso-commsgw", + }, + }); + Response response = await client.CreateOrReplaceNumberAsync("contoso", "+15105850321", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_CreateOrReplaceNumber_CreateOrReplaceANumber_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + NumberResource resource = new NumberResource("+15105850321", "contoso", new NumberServiceDetails + { + TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) + { + AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, + Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[] { "InboundCalling" }), + }, + }) + { + Configuration = new NumberConfiguration + { + CustomSipHeader = "contoso-commsgw", + }, + }; + Response response = client.CreateOrReplaceNumber("contoso", "+15105850321", resource); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_CreateOrReplaceNumber_CreateOrReplaceANumber_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + NumberResource resource = new NumberResource("+15105850321", "contoso", new NumberServiceDetails + { + TeamsOperatorConnect = new TeamsOperatorConnectNumberDetails(true) + { + AssignmentStatus = TelephoneNumberAssignmentStatus.Assigned, + Configuration = new TeamsOperatorConnectNumberConfig("CallingUserAssignment", new string[] { "InboundCalling" }), + }, + }) + { + Configuration = new NumberConfiguration + { + CustomSipHeader = "contoso-commsgw", + }, + }; + Response response = await client.CreateOrReplaceNumberAsync("contoso", "+15105850321", resource); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_DeleteNumber_DeleteNumberFromAccount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.DeleteNumber("contoso", "+15105850321"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_DeleteNumber_DeleteNumberFromAccount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.DeleteNumberAsync("contoso", "+15105850321"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_GetTeamsCapabilityPlans_GetTheListOfCapabilityPlansAvailableToThisAccount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetTeamsCapabilityPlans("contoso", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("usage").ToString()); + Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("supportsTollFree").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_GetTeamsCapabilityPlans_GetTheListOfCapabilityPlansAvailableToThisAccount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetTeamsCapabilityPlansAsync("contoso", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("usage").ToString()); + Console.WriteLine(result.GetProperty("capabilityPlans")[0].GetProperty("supportsTollFree").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_GetTeamsCapabilityPlans_GetTheListOfCapabilityPlansAvailableToThisAccount_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetTeamsCapabilityPlans("contoso"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_GetTeamsCapabilityPlans_GetTheListOfCapabilityPlansAvailableToThisAccount_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetTeamsCapabilityPlansAsync("contoso"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_GetTeamsAvailableCapabilities_GetTheTeamsCapabilitiesAvailableToTheNumbersProvided() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + numbers = new object[] + { +new +{ +telephoneNumber = "+15105850321", +} + }, + }); + Response response = client.GetTeamsAvailableCapabilities("contoso", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("availableCapabilities")[0].ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_GetTeamsAvailableCapabilities_GetTheTeamsCapabilitiesAvailableToTheNumbersProvided_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + using RequestContent content = RequestContent.Create(new + { + numbers = new object[] + { +new +{ +telephoneNumber = "+15105850321", +} + }, + }); + Response response = await client.GetTeamsAvailableCapabilitiesAsync("contoso", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("availableCapabilities")[0].ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_Accounts_GetTeamsAvailableCapabilities_GetTheTeamsCapabilitiesAvailableToTheNumbersProvided_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + NumberIdentifiers body = new NumberIdentifiers(new NumberIdentifier[] + { +new NumberIdentifier("+15105850321") + }); + Response response = client.GetTeamsAvailableCapabilities("contoso", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_Accounts_GetTeamsAvailableCapabilities_GetTheTeamsCapabilitiesAvailableToTheNumbersProvided_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + NumberIdentifiers body = new NumberIdentifiers(new NumberIdentifier[] + { +new NumberIdentifier("+15105850321") + }); + Response response = await client.GetTeamsAvailableCapabilitiesAsync("contoso", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_TeamsCivicAddressResource_GetTeamsCivicAddress_GetACivicAddress() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetTeamsCivicAddress("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_TeamsCivicAddressResource_GetTeamsCivicAddress_GetACivicAddress_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetTeamsCivicAddressAsync("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_TeamsCivicAddressResource_GetTeamsCivicAddress_GetACivicAddress_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = client.GetTeamsCivicAddress("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_TeamsCivicAddressResource_GetTeamsCivicAddress_GetACivicAddress_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + Response response = await client.GetTeamsCivicAddressAsync("contoso", "ebfee340-a791-11ed-9bfa-ed8bb5c41be4"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_AccountResource_GetAccountResources_GetListOfAccounts() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + foreach (BinaryData item in client.GetAccountResources(null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_AccountResource_GetAccountResources_GetListOfAccounts_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + await foreach (BinaryData item in client.GetAccountResourcesAsync(null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_AccountResource_GetAccountResources_GetListOfAccounts_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + foreach (AccountResource item in client.GetAccountResources()) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_AccountResource_GetAccountResources_GetListOfAccounts_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + await foreach (AccountResource item in client.GetAccountResourcesAsync()) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_GetNumbers_GetListOfNumbersOnAnAccount() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + foreach (BinaryData item in client.GetNumbers("contoso", null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_GetNumbers_GetListOfNumbersOnAnAccount_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + await foreach (BinaryData item in client.GetNumbersAsync("contoso", null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_GetNumbers_GetListOfNumbersOnAnAccount_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + foreach (NumberResource item in client.GetNumbers("contoso")) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_GetNumbers_GetListOfNumbersOnAnAccount_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + await foreach (NumberResource item in client.GetNumbersAsync("contoso")) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_TeamsCivicAddressResource_GetTeamsCivicAddresses_GetAListOfCivicAddresses() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + foreach (BinaryData item in client.GetTeamsCivicAddresses("contoso", null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_TeamsCivicAddressResource_GetTeamsCivicAddresses_GetAListOfCivicAddresses_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + await foreach (BinaryData item in client.GetTeamsCivicAddressesAsync("contoso", null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("defaultLocationId").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_TeamsCivicAddressResource_GetTeamsCivicAddresses_GetAListOfCivicAddresses_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + foreach (TeamsCivicAddressResource item in client.GetTeamsCivicAddresses("contoso")) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_TeamsCivicAddressResource_GetTeamsCivicAddresses_GetAListOfCivicAddresses_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + Accounts client = new VoiceServicesClient(endpoint, credential).GetAccountsClient(); + + await foreach (TeamsCivicAddressResource item in client.GetTeamsCivicAddressesAsync("contoso")) + { + } + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_TeamsRequestsForInformation.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_TeamsRequestsForInformation.cs new file mode 100644 index 000000000000..d09e2a4813dc --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_TeamsRequestsForInformation.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Microsoft.VoiceServices.Provisioning.Samples +{ + public partial class Samples_TeamsRequestsForInformation + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RequestForInformationResource_GetRequestForInformation_GetAnRFIByTenantID() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + Response response = client.GetRequestForInformation("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RequestForInformationResource_GetRequestForInformation_GetAnRFIByTenantID_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + Response response = await client.GetRequestForInformationAsync("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", null, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RequestForInformationResource_GetRequestForInformation_GetAnRFIByTenantID_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + Response response = client.GetRequestForInformation("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RequestForInformationResource_GetRequestForInformation_GetAnRFIByTenantID_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + Response response = await client.GetRequestForInformationAsync("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RequestForInformationResource_CreateOrUpdateRequestForInformation_CreateOrUpdateATeamsRequestForInformation() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + using RequestContent content = RequestContent.Create(new + { + customerRelationship = new + { + status = "ConsentAcknowledged", + comment = "Consent has been accepted on 2024-01-12", + }, + }); + Response response = client.CreateOrUpdateRequestForInformation("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RequestForInformationResource_CreateOrUpdateRequestForInformation_CreateOrUpdateATeamsRequestForInformation_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + using RequestContent content = RequestContent.Create(new + { + customerRelationship = new + { + status = "ConsentAcknowledged", + comment = "Consent has been accepted on 2024-01-12", + }, + }); + Response response = await client.CreateOrUpdateRequestForInformationAsync("a7f4bd5c-cc01-40f4-8baa-2b6bdb272b8a", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RequestForInformationResource_GetRequestForInformationResources_GetListOfRequestsForInformationConsents() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + foreach (BinaryData item in client.GetRequestForInformationResources(null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RequestForInformationResource_GetRequestForInformationResources_GetListOfRequestsForInformationConsents_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + await foreach (BinaryData item in client.GetRequestForInformationResourcesAsync(null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("tenantId").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_RequestForInformationResource_GetRequestForInformationResources_GetListOfRequestsForInformationConsents_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + foreach (RequestForInformationResource item in client.GetRequestForInformationResources()) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_RequestForInformationResource_GetRequestForInformationResources_GetListOfRequestsForInformationConsents_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + TeamsRequestsForInformation client = new VoiceServicesClient(endpoint, credential).GetTeamsRequestsForInformationClient(); + + await foreach (RequestForInformationResource item in client.GetRequestForInformationResourcesAsync()) + { + } + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_VoiceServicesClient.cs b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_VoiceServicesClient.cs new file mode 100644 index 000000000000..bd3aa465903e --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Generated/Samples/Samples_VoiceServicesClient.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Microsoft.VoiceServices.Provisioning.Samples +{ + public partial class Samples_VoiceServicesClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_GetNumbers_GetListOfNumbersFromAllAccounts() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + + foreach (BinaryData item in client.GetNumbers(null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_GetNumbers_GetListOfNumbersFromAllAccounts_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + + await foreach (BinaryData item in client.GetNumbersAsync(null, null, null, null, true, null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("telephoneNumber").ToString()); + Console.WriteLine(result.GetProperty("accountName").ToString()); + Console.WriteLine(result.GetProperty("serviceDetails").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberResource_GetNumbers_GetListOfNumbersFromAllAccounts_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + + foreach (NumberResource item in client.GetNumbers()) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberResource_GetNumbers_GetListOfNumbersFromAllAccounts_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + VoiceServicesClient client = new VoiceServicesClient(endpoint, credential); + + await foreach (NumberResource item in client.GetNumbersAsync()) + { + } + } + } +} diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Microsoft.VoiceServices.Provisioning.Tests.csproj b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Microsoft.VoiceServices.Provisioning.Tests.csproj new file mode 100644 index 000000000000..de28dc09a86a --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tests/Microsoft.VoiceServices.Provisioning.Tests.csproj @@ -0,0 +1,19 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tsp-location.yaml b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tsp-location.yaml new file mode 100644 index 000000000000..bcef2ce71423 --- /dev/null +++ b/sdk/2024-02-29-preview/Microsoft.VoiceServices.Provisioning/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/voiceservices/VoiceServices.Provisioning +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/apicenter/azure.ApiCenter/Configuration.json b/sdk/apicenter/azure.ApiCenter/Configuration.json new file mode 100644 index 000000000000..485b7a85641c --- /dev/null +++ b/sdk/apicenter/azure.ApiCenter/Configuration.json @@ -0,0 +1,12 @@ +{ + "output-folder": ".", + "namespace": "azure.ApiCenter", + "library-name": "azure.ApiCenter", + "flavor": "azure", + "use-model-reader-writer": true, + "shared-source-folders": [ + "../../TempTypeSpecFiles/node_modules/@autorest/csharp/Generator.Shared", + "../../TempTypeSpecFiles/node_modules/@autorest/csharp/Azure.Core.Shared" + ], + "model-namespace": false +} diff --git a/sdk/apicenter/azure.ApiCenter/tsp-location.yaml b/sdk/apicenter/azure.ApiCenter/tsp-location.yaml new file mode 100644 index 000000000000..382418cecf17 --- /dev/null +++ b/sdk/apicenter/azure.ApiCenter/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/apicenter/ApiCenter.DataApi +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/apicenter/azure.ApiCenter/tspCodeModel.json b/sdk/apicenter/azure.ApiCenter/tspCodeModel.json new file mode 100644 index 000000000000..aad4a23566c0 --- /dev/null +++ b/sdk/apicenter/azure.ApiCenter/tspCodeModel.json @@ -0,0 +1,8146 @@ +{ + "$id": "1", + "name": "ApiCenter.DataApi", + "apiVersions": [ + "2024-02-01-preview" + ], + "enums": [ + { + "$id": "2", + "kind": "enum", + "name": "LifecycleStage", + "crossLanguageDefinitionId": "ApiCenter.DataApi.LifecycleStage", + "valueType": { + "$id": "3", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "4", + "kind": "enumvalue", + "name": "Design", + "value": "design", + "valueType": { + "$id": "5", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "doc": "API is in the design stage", + "decorators": [] + }, + { + "$id": "6", + "kind": "enumvalue", + "name": "Development", + "value": "development", + "valueType": { + "$id": "7", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "doc": "API is in the development stage", + "decorators": [] + }, + { + "$id": "8", + "kind": "enumvalue", + "name": "Testing", + "value": "testing", + "valueType": { + "$id": "9", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "doc": "API is in the testing stage", + "decorators": [] + }, + { + "$id": "10", + "kind": "enumvalue", + "name": "Preview", + "value": "preview", + "valueType": { + "$id": "11", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "doc": "API is in the preview stage", + "decorators": [] + }, + { + "$id": "12", + "kind": "enumvalue", + "name": "Production", + "value": "production", + "valueType": { + "$id": "13", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "doc": "API is in the production stage", + "decorators": [] + }, + { + "$id": "14", + "kind": "enumvalue", + "name": "Deprecated", + "value": "deprecated", + "valueType": { + "$id": "15", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "doc": "API is in the deprecated stage", + "decorators": [] + }, + { + "$id": "16", + "kind": "enumvalue", + "name": "Retired", + "value": "retired", + "valueType": { + "$id": "17", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "doc": "API is in the retired stage", + "decorators": [] + } + ], + "namespace": "azure.ApiCenter", + "doc": "API Lifecycle Stage", + "isFixed": false, + "isFlags": false, + "usage": "Output,Json", + "decorators": [] + }, + { + "$id": "18", + "kind": "enum", + "name": "EnvironmentKind", + "crossLanguageDefinitionId": "ApiCenter.DataApi.EnvironmentKind", + "valueType": { + "$id": "19", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "20", + "kind": "enumvalue", + "name": "Development", + "value": "development", + "valueType": { + "$id": "21", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "18" + }, + "doc": "Environment is in the development stage", + "decorators": [] + }, + { + "$id": "22", + "kind": "enumvalue", + "name": "Testing", + "value": "testing", + "valueType": { + "$id": "23", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "18" + }, + "doc": "Environment is in the testing stage", + "decorators": [] + }, + { + "$id": "24", + "kind": "enumvalue", + "name": "Staging", + "value": "staging", + "valueType": { + "$id": "25", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "18" + }, + "doc": "Environment is in the staging stage", + "decorators": [] + }, + { + "$id": "26", + "kind": "enumvalue", + "name": "Production", + "value": "production", + "valueType": { + "$id": "27", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "18" + }, + "doc": "Environment is in the production stage", + "decorators": [] + } + ], + "namespace": "azure.ApiCenter", + "doc": "Environment kind", + "isFixed": false, + "isFlags": false, + "usage": "Output,Json", + "decorators": [] + }, + { + "$id": "28", + "kind": "enum", + "name": "ApiSpecExportResultFormat", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecExportResultFormat", + "valueType": { + "$id": "29", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "30", + "kind": "enumvalue", + "name": "Link", + "value": "link", + "valueType": { + "$id": "31", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "28" + }, + "doc": "Link format", + "decorators": [] + } + ], + "namespace": "azure.ApiCenter", + "doc": "Export specification result format", + "isFixed": false, + "isFlags": false, + "usage": "Output,Json,LroInitial,LroPolling,LroFinalEnvelope", + "decorators": [] + }, + { + "$id": "32", + "kind": "enum", + "name": "ApiKind", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiKind", + "valueType": { + "$id": "33", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "34", + "kind": "enumvalue", + "name": "Rest", + "value": "rest", + "valueType": { + "$id": "35", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "doc": "REST API", + "decorators": [] + }, + { + "$id": "36", + "kind": "enumvalue", + "name": "Graphql", + "value": "graphql", + "valueType": { + "$id": "37", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "doc": "GraphQL API", + "decorators": [] + }, + { + "$id": "38", + "kind": "enumvalue", + "name": "Grpc", + "value": "grpc", + "valueType": { + "$id": "39", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "doc": "GRPC API", + "decorators": [] + }, + { + "$id": "40", + "kind": "enumvalue", + "name": "Soap", + "value": "soap", + "valueType": { + "$id": "41", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "doc": "SOAP API", + "decorators": [] + }, + { + "$id": "42", + "kind": "enumvalue", + "name": "Webhook", + "value": "webhook", + "valueType": { + "$id": "43", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "doc": "Webhook API", + "decorators": [] + }, + { + "$id": "44", + "kind": "enumvalue", + "name": "Websocket", + "value": "websocket", + "valueType": { + "$id": "45", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "doc": "Websocket API", + "decorators": [] + } + ], + "namespace": "azure.ApiCenter", + "doc": "API kind", + "isFixed": false, + "isFlags": false, + "usage": "Output,Json", + "decorators": [] + }, + { + "$id": "46", + "kind": "enum", + "name": "Versions", + "crossLanguageDefinitionId": "ApiCenter.DataApi.Versions", + "valueType": { + "$id": "47", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "48", + "kind": "enumvalue", + "name": "v2024_02_01_preview", + "value": "2024-02-01-preview", + "valueType": { + "$id": "49", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "46" + }, + "doc": "Preview release version 2024-02-01-preview", + "decorators": [] + } + ], + "namespace": "azure.ApiCenter", + "doc": "API versions", + "isFixed": true, + "isFlags": false, + "usage": "ApiVersionEnum", + "decorators": [] + }, + { + "$id": "50", + "kind": "enum", + "name": "OperationState", + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationState", + "valueType": { + "$id": "51", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "52", + "kind": "enumvalue", + "name": "NotStarted", + "value": "NotStarted", + "valueType": { + "$id": "53", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "50" + }, + "doc": "The operation has not started.", + "decorators": [] + }, + { + "$id": "54", + "kind": "enumvalue", + "name": "Running", + "value": "Running", + "valueType": { + "$id": "55", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "50" + }, + "doc": "The operation is in progress.", + "decorators": [] + }, + { + "$id": "56", + "kind": "enumvalue", + "name": "Succeeded", + "value": "Succeeded", + "valueType": { + "$id": "57", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "50" + }, + "doc": "The operation has completed successfully.", + "decorators": [] + }, + { + "$id": "58", + "kind": "enumvalue", + "name": "Failed", + "value": "Failed", + "valueType": { + "$id": "59", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "50" + }, + "doc": "The operation has failed.", + "decorators": [] + }, + { + "$id": "60", + "kind": "enumvalue", + "name": "Canceled", + "value": "Canceled", + "valueType": { + "$id": "61", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "50" + }, + "doc": "The operation has been canceled by the user.", + "decorators": [] + } + ], + "namespace": "azure.ApiCenter", + "doc": "Enum describing allowed operation states.", + "isFixed": false, + "isFlags": false, + "usage": "Output,Json,LroInitial,LroPolling,LroFinalEnvelope", + "decorators": [] + } + ], + "models": [ + { + "$id": "62", + "kind": "model", + "name": "ApiVersion", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiVersion", + "usage": "Output,Json", + "doc": "API version resource model.", + "decorators": [], + "properties": [ + { + "$id": "63", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "Version identifier.", + "type": { + "$id": "64", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiVersion.name", + "serializationOptions": { + "$id": "65", + "json": { + "$id": "66", + "name": "name" + } + } + }, + { + "$id": "67", + "kind": "property", + "name": "title", + "serializedName": "title", + "doc": "Version title.", + "type": { + "$id": "68", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiVersion.title", + "serializationOptions": { + "$id": "69", + "json": { + "$id": "70", + "name": "title" + } + } + }, + { + "$id": "71", + "kind": "property", + "name": "lifecycleStage", + "serializedName": "lifecycleStage", + "doc": "Current lifecycle stage of the API version.", + "type": { + "$ref": "2" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiVersion.lifecycleStage", + "serializationOptions": { + "$id": "72", + "json": { + "$id": "73", + "name": "lifecycleStage" + } + } + } + ] + }, + { + "$id": "74", + "kind": "model", + "name": "Environment", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment", + "usage": "Output,Json", + "doc": "Environment resource model.", + "decorators": [], + "properties": [ + { + "$id": "75", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "Environment identifier.", + "type": { + "$id": "76", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.name", + "serializationOptions": { + "$id": "77", + "json": { + "$id": "78", + "name": "name" + } + } + }, + { + "$id": "79", + "kind": "property", + "name": "title", + "serializedName": "title", + "doc": "The name of the environment.", + "type": { + "$id": "80", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.title", + "serializationOptions": { + "$id": "81", + "json": { + "$id": "82", + "name": "title" + } + } + }, + { + "$id": "83", + "kind": "property", + "name": "kind", + "serializedName": "kind", + "doc": "Kind of deployment environment.", + "type": { + "$ref": "18" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.kind", + "serializationOptions": { + "$id": "84", + "json": { + "$id": "85", + "name": "kind" + } + } + }, + { + "$id": "86", + "kind": "property", + "name": "description", + "serializedName": "description", + "doc": "Description of the environment.", + "type": { + "$id": "87", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.description", + "serializationOptions": { + "$id": "88", + "json": { + "$id": "89", + "name": "description" + } + } + }, + { + "$id": "90", + "kind": "property", + "name": "server", + "serializedName": "server", + "doc": "Server information of the environment.", + "type": { + "$id": "91", + "kind": "model", + "name": "EnvironmentServer", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.EnvironmentServer", + "usage": "Output,Json", + "doc": "Environment Server", + "decorators": [], + "properties": [ + { + "$id": "92", + "kind": "property", + "name": "type", + "serializedName": "type", + "doc": "Type of the server that represents the environment.", + "type": { + "$id": "93", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.EnvironmentServer.type", + "serializationOptions": { + "$id": "94", + "json": { + "$id": "95", + "name": "type" + } + } + }, + { + "$id": "96", + "kind": "property", + "name": "managementPortalUris", + "serializedName": "managementPortalUris", + "doc": "URIs of the server's management portal.", + "type": { + "$id": "97", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "98", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.EnvironmentServer.managementPortalUris", + "serializationOptions": { + "$id": "99", + "json": { + "$id": "100", + "name": "managementPortalUris" + } + } + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.server", + "serializationOptions": { + "$id": "101", + "json": { + "$id": "102", + "name": "server" + } + } + }, + { + "$id": "103", + "kind": "property", + "name": "onboarding", + "serializedName": "onboarding", + "doc": "Onboarding information for this environment.", + "type": { + "$id": "104", + "kind": "model", + "name": "EnvironmentOnboardingModel", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.EnvironmentOnboardingModel", + "usage": "Output,Json", + "doc": "Environment Onboarding Model", + "decorators": [], + "properties": [ + { + "$id": "105", + "kind": "property", + "name": "instructions", + "serializedName": "instructions", + "doc": "Instructions how to onboard to the environment.", + "type": { + "$id": "106", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.EnvironmentOnboardingModel.instructions", + "serializationOptions": { + "$id": "107", + "json": { + "$id": "108", + "name": "instructions" + } + } + }, + { + "$id": "109", + "kind": "property", + "name": "developerPortalUris", + "serializedName": "developerPortalUris", + "doc": "Developer portal URIs of the environment.", + "type": { + "$id": "110", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "111", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.EnvironmentOnboardingModel.developerPortalUris", + "serializationOptions": { + "$id": "112", + "json": { + "$id": "113", + "name": "developerPortalUris" + } + } + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.onboarding", + "serializationOptions": { + "$id": "114", + "json": { + "$id": "115", + "name": "onboarding" + } + } + }, + { + "$id": "116", + "kind": "property", + "name": "customProperties", + "serializedName": "customProperties", + "doc": "The custom metadata defined for environment entities.", + "type": { + "$id": "117", + "kind": "model", + "name": "EnvironmentCustomProperties", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.customProperties.anonymous", + "usage": "Output,Json", + "decorators": [], + "properties": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environment.customProperties", + "serializationOptions": { + "$id": "118", + "json": { + "$id": "119", + "name": "customProperties" + } + } + } + ] + }, + { + "$ref": "91" + }, + { + "$ref": "104" + }, + { + "$ref": "117" + }, + { + "$id": "120", + "kind": "model", + "name": "PagedEnvironmentAll", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.PagedEnvironmentAll", + "usage": "Output,Json", + "doc": "Paged collection of Environment items across workspaces", + "decorators": [], + "properties": [ + { + "$id": "121", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The Environment items on this page", + "type": { + "$id": "122", + "kind": "array", + "name": "ArrayEnvironment", + "valueType": { + "$ref": "74" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.PagedEnvironmentAll.value", + "serializationOptions": { + "$id": "123", + "json": { + "$id": "124", + "name": "value" + } + } + }, + { + "$id": "125", + "kind": "property", + "name": "nextLink", + "serializedName": "nextLink", + "doc": "The link to the next page of items", + "type": { + "$id": "126", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "127", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.PagedEnvironmentAll.nextLink", + "serializationOptions": { + "$id": "128", + "json": { + "$id": "129", + "name": "nextLink" + } + } + } + ] + }, + { + "$id": "130", + "kind": "model", + "name": "ApiDeployment", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment", + "usage": "Output,Json", + "doc": "API deployment resource model.", + "decorators": [], + "properties": [ + { + "$id": "131", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "Deployment identifier.", + "type": { + "$id": "132", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.name", + "serializationOptions": { + "$id": "133", + "json": { + "$id": "134", + "name": "name" + } + } + }, + { + "$id": "135", + "kind": "property", + "name": "title", + "serializedName": "title", + "doc": "The name of the deployment.", + "type": { + "$id": "136", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.title", + "serializationOptions": { + "$id": "137", + "json": { + "$id": "138", + "name": "title" + } + } + }, + { + "$id": "139", + "kind": "property", + "name": "description", + "serializedName": "description", + "doc": "The description of the deployment.", + "type": { + "$id": "140", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.description", + "serializationOptions": { + "$id": "141", + "json": { + "$id": "142", + "name": "description" + } + } + }, + { + "$id": "143", + "kind": "property", + "name": "environment", + "serializedName": "environment", + "doc": "The name of the deployment environment.", + "type": { + "$id": "144", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.environment", + "serializationOptions": { + "$id": "145", + "json": { + "$id": "146", + "name": "environment" + } + } + }, + { + "$id": "147", + "kind": "property", + "name": "server", + "serializedName": "server", + "doc": "The server information of the API deployment.", + "type": { + "$id": "148", + "kind": "model", + "name": "ApiDeploymentServer", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeploymentServer", + "usage": "Output,Json", + "doc": "Api Deployment Server", + "decorators": [], + "properties": [ + { + "$id": "149", + "kind": "property", + "name": "runtimeUris", + "serializedName": "runtimeUris", + "doc": "Base runtime URIs for this deployment.", + "type": { + "$id": "150", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "151", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeploymentServer.runtimeUris", + "serializationOptions": { + "$id": "152", + "json": { + "$id": "153", + "name": "runtimeUris" + } + } + } + ] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.server", + "serializationOptions": { + "$id": "154", + "json": { + "$id": "155", + "name": "server" + } + } + }, + { + "$id": "156", + "kind": "property", + "name": "customProperties", + "serializedName": "customProperties", + "doc": "The custom metadata defined for API deployment entities.", + "type": { + "$id": "157", + "kind": "model", + "name": "ApiDeploymentCustomProperties", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.customProperties.anonymous", + "usage": "Output,Json", + "decorators": [], + "properties": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.customProperties", + "serializationOptions": { + "$id": "158", + "json": { + "$id": "159", + "name": "customProperties" + } + } + }, + { + "$id": "160", + "kind": "property", + "name": "recommended", + "serializedName": "recommended", + "doc": "Indicates if this is currently recommended deployment.", + "type": { + "$id": "161", + "kind": "boolean", + "name": "boolean", + "crossLanguageDefinitionId": "TypeSpec.boolean", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployment.recommended", + "serializationOptions": { + "$id": "162", + "json": { + "$id": "163", + "name": "recommended" + } + } + } + ] + }, + { + "$ref": "148" + }, + { + "$ref": "157" + }, + { + "$id": "164", + "kind": "model", + "name": "ApiDefinition", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinition", + "usage": "Output,Json", + "doc": "API definition resource model.", + "decorators": [], + "properties": [ + { + "$id": "165", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "Definition identifier.", + "type": { + "$id": "166", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinition.name", + "serializationOptions": { + "$id": "167", + "json": { + "$id": "168", + "name": "name" + } + } + }, + { + "$id": "169", + "kind": "property", + "name": "title", + "serializedName": "title", + "doc": "The name of the API definition.", + "type": { + "$id": "170", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinition.title", + "serializationOptions": { + "$id": "171", + "json": { + "$id": "172", + "name": "title" + } + } + }, + { + "$id": "173", + "kind": "property", + "name": "description", + "serializedName": "description", + "doc": "The description of the API definition.", + "type": { + "$id": "174", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinition.description", + "serializationOptions": { + "$id": "175", + "json": { + "$id": "176", + "name": "description" + } + } + }, + { + "$id": "177", + "kind": "property", + "name": "specification", + "serializedName": "specification", + "doc": "The API specification details.", + "type": { + "$id": "178", + "kind": "model", + "name": "ApiSpecification", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecification", + "usage": "Output,Json", + "doc": "API specification", + "decorators": [], + "properties": [ + { + "$id": "179", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "API specification name, e.g. 'swagger' or 'openapi'.", + "type": { + "$id": "180", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecification.name", + "serializationOptions": { + "$id": "181", + "json": { + "$id": "182", + "name": "name" + } + } + }, + { + "$id": "183", + "kind": "property", + "name": "version", + "serializedName": "version", + "doc": "API specification version, e.g. '3.0.1'.", + "type": { + "$id": "184", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecification.version", + "serializationOptions": { + "$id": "185", + "json": { + "$id": "186", + "name": "version" + } + } + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinition.specification", + "serializationOptions": { + "$id": "187", + "json": { + "$id": "188", + "name": "specification" + } + } + } + ] + }, + { + "$ref": "178" + }, + { + "$id": "189", + "kind": "model", + "name": "ApiSpecExportResult", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecExportResult", + "usage": "Output,Json,LroInitial,LroPolling,LroFinalEnvelope", + "doc": "Export specification result model.", + "decorators": [], + "properties": [ + { + "$id": "190", + "kind": "property", + "name": "definitionName", + "serializedName": "definitionName", + "doc": "API definition identifier.", + "type": { + "$id": "191", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecExportResult.definitionName", + "serializationOptions": { + "$id": "192", + "json": { + "$id": "193", + "name": "definitionName" + } + } + }, + { + "$id": "194", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The result of the specification export.", + "type": { + "$id": "195", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecExportResult.value", + "serializationOptions": { + "$id": "196", + "json": { + "$id": "197", + "name": "value" + } + } + }, + { + "$id": "198", + "kind": "property", + "name": "format", + "serializedName": "format", + "doc": "The format of the specification export result.", + "type": { + "$ref": "28" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiSpecExportResult.format", + "serializationOptions": { + "$id": "199", + "json": { + "$id": "200", + "name": "format" + } + } + } + ] + }, + { + "$id": "201", + "kind": "model", + "name": "Api", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api", + "usage": "Output,Json", + "doc": "API resource model.", + "decorators": [], + "properties": [ + { + "$id": "202", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "Api identifier.", + "type": { + "$id": "203", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.name", + "serializationOptions": { + "$id": "204", + "json": { + "$id": "205", + "name": "name" + } + } + }, + { + "$id": "206", + "kind": "property", + "name": "title", + "serializedName": "title", + "doc": "The name of the API.", + "type": { + "$id": "207", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.title", + "serializationOptions": { + "$id": "208", + "json": { + "$id": "209", + "name": "title" + } + } + }, + { + "$id": "210", + "kind": "property", + "name": "summary", + "serializedName": "summary", + "doc": "Short description of the API.", + "type": { + "$id": "211", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.summary", + "serializationOptions": { + "$id": "212", + "json": { + "$id": "213", + "name": "summary" + } + } + }, + { + "$id": "214", + "kind": "property", + "name": "description", + "serializedName": "description", + "doc": "The description of the API", + "type": { + "$id": "215", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.description", + "serializationOptions": { + "$id": "216", + "json": { + "$id": "217", + "name": "description" + } + } + }, + { + "$id": "218", + "kind": "property", + "name": "kind", + "serializedName": "kind", + "doc": "Kind of API. For example, REST or GraphQL.", + "type": { + "$ref": "32" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.kind", + "serializationOptions": { + "$id": "219", + "json": { + "$id": "220", + "name": "kind" + } + } + }, + { + "$id": "221", + "kind": "property", + "name": "lifecycleStage", + "serializedName": "lifecycleStage", + "doc": "Current lifecycle stage of the API.", + "type": { + "$ref": "2" + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.lifecycleStage", + "serializationOptions": { + "$id": "222", + "json": { + "$id": "223", + "name": "lifecycleStage" + } + } + }, + { + "$id": "224", + "kind": "property", + "name": "termsOfService", + "serializedName": "termsOfService", + "doc": "Terms of service for the API.", + "type": { + "$id": "225", + "kind": "model", + "name": "TermsOfService", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.TermsOfService", + "usage": "Output,Json", + "doc": "API Terms of Service", + "decorators": [], + "properties": [ + { + "$id": "226", + "kind": "property", + "name": "url", + "serializedName": "url", + "doc": "URL pointing to the terms of service.", + "type": { + "$id": "227", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.TermsOfService.url", + "serializationOptions": { + "$id": "228", + "json": { + "$id": "229", + "name": "url" + } + } + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.termsOfService", + "serializationOptions": { + "$id": "230", + "json": { + "$id": "231", + "name": "termsOfService" + } + } + }, + { + "$id": "232", + "kind": "property", + "name": "license", + "serializedName": "license", + "doc": "The license information for the API.", + "type": { + "$id": "233", + "kind": "model", + "name": "License", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.License", + "usage": "Output,Json", + "doc": "API License Model", + "decorators": [], + "properties": [ + { + "$id": "234", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "Name of the license.", + "type": { + "$id": "235", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.License.name", + "serializationOptions": { + "$id": "236", + "json": { + "$id": "237", + "name": "name" + } + } + }, + { + "$id": "238", + "kind": "property", + "name": "url", + "serializedName": "url", + "doc": "URL pointing to the license details. The URL field is mutually exclusive of the identifier field.", + "type": { + "$id": "239", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.License.url", + "serializationOptions": { + "$id": "240", + "json": { + "$id": "241", + "name": "url" + } + } + }, + { + "$id": "242", + "kind": "property", + "name": "identifier", + "serializedName": "identifier", + "doc": "SPDX license information for the API. The identifier field is mutually exclusive of the URL field.", + "type": { + "$id": "243", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.License.identifier", + "serializationOptions": { + "$id": "244", + "json": { + "$id": "245", + "name": "identifier" + } + } + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.license", + "serializationOptions": { + "$id": "246", + "json": { + "$id": "247", + "name": "license" + } + } + }, + { + "$id": "248", + "kind": "property", + "name": "externalDocumentation", + "serializedName": "externalDocumentation", + "doc": "External documentation", + "type": { + "$id": "249", + "kind": "array", + "name": "ArrayExternalDocumentation", + "valueType": { + "$id": "250", + "kind": "model", + "name": "ExternalDocumentation", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.ExternalDocumentation", + "usage": "Output,Json", + "doc": "Api External Documentation Model", + "decorators": [], + "properties": [ + { + "$id": "251", + "kind": "property", + "name": "title", + "serializedName": "title", + "doc": "Title of the documentation.", + "type": { + "$id": "252", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ExternalDocumentation.title", + "serializationOptions": { + "$id": "253", + "json": { + "$id": "254", + "name": "title" + } + } + }, + { + "$id": "255", + "kind": "property", + "name": "description", + "serializedName": "description", + "doc": "Description of the documentation.", + "type": { + "$id": "256", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ExternalDocumentation.description", + "serializationOptions": { + "$id": "257", + "json": { + "$id": "258", + "name": "description" + } + } + }, + { + "$id": "259", + "kind": "property", + "name": "url", + "serializedName": "url", + "doc": "URL pointing to the documentation.", + "type": { + "$id": "260", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ExternalDocumentation.url", + "serializationOptions": { + "$id": "261", + "json": { + "$id": "262", + "name": "url" + } + } + } + ] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.externalDocumentation", + "serializationOptions": { + "$id": "263", + "json": { + "$id": "264", + "name": "externalDocumentation" + } + } + }, + { + "$id": "265", + "kind": "property", + "name": "contacts", + "serializedName": "contacts", + "doc": "Points of contact for the API.", + "type": { + "$id": "266", + "kind": "array", + "name": "ArrayContact", + "valueType": { + "$id": "267", + "kind": "model", + "name": "Contact", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.Contact", + "usage": "Output,Json", + "doc": "API contact information", + "decorators": [], + "properties": [ + { + "$id": "268", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "Name of the contact.", + "type": { + "$id": "269", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Contact.name", + "serializationOptions": { + "$id": "270", + "json": { + "$id": "271", + "name": "name" + } + } + }, + { + "$id": "272", + "kind": "property", + "name": "url", + "serializedName": "url", + "doc": "URL for the contact.", + "type": { + "$id": "273", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Contact.url", + "serializationOptions": { + "$id": "274", + "json": { + "$id": "275", + "name": "url" + } + } + }, + { + "$id": "276", + "kind": "property", + "name": "email", + "serializedName": "email", + "doc": "Email address for the contact.", + "type": { + "$id": "277", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Contact.email", + "serializationOptions": { + "$id": "278", + "json": { + "$id": "279", + "name": "email" + } + } + } + ] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.contacts", + "serializationOptions": { + "$id": "280", + "json": { + "$id": "281", + "name": "contacts" + } + } + }, + { + "$id": "282", + "kind": "property", + "name": "customProperties", + "serializedName": "customProperties", + "doc": "The custom metadata defined for API entities.", + "type": { + "$id": "283", + "kind": "model", + "name": "ApiCustomProperties", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.customProperties.anonymous", + "usage": "Output,Json", + "decorators": [], + "properties": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.customProperties", + "serializationOptions": { + "$id": "284", + "json": { + "$id": "285", + "name": "customProperties" + } + } + }, + { + "$id": "286", + "kind": "property", + "name": "lastUpdated", + "serializedName": "lastUpdated", + "doc": "Last updated date and time.", + "type": { + "$id": "287", + "kind": "utcDateTime", + "name": "utcDateTime", + "encode": "rfc3339", + "wireType": { + "$id": "288", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.utcDateTime", + "decorators": [] + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Api.lastUpdated", + "serializationOptions": { + "$id": "289", + "json": { + "$id": "290", + "name": "lastUpdated" + } + } + } + ] + }, + { + "$ref": "225" + }, + { + "$ref": "233" + }, + { + "$ref": "250" + }, + { + "$ref": "267" + }, + { + "$ref": "283" + }, + { + "$id": "291", + "kind": "model", + "name": "PagedApiAll", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "ApiCenter.DataApi.PagedApiAll", + "usage": "Output,Json", + "doc": "Paged collection of API items across workspaces.", + "decorators": [], + "properties": [ + { + "$id": "292", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The Api items on this page", + "type": { + "$id": "293", + "kind": "array", + "name": "ArrayApi", + "valueType": { + "$ref": "201" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.PagedApiAll.value", + "serializationOptions": { + "$id": "294", + "json": { + "$id": "295", + "name": "value" + } + } + }, + { + "$id": "296", + "kind": "property", + "name": "nextLink", + "serializedName": "nextLink", + "doc": "The link to the next page of items", + "type": { + "$id": "297", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "298", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.PagedApiAll.nextLink", + "serializationOptions": { + "$id": "299", + "json": { + "$id": "300", + "name": "nextLink" + } + } + } + ] + }, + { + "$id": "301", + "kind": "model", + "name": "PagedApi", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage", + "usage": "Output,Json", + "doc": "Paged collection of Api items", + "decorators": [], + "properties": [ + { + "$id": "302", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The Api items on this page", + "type": { + "$id": "303", + "kind": "array", + "name": "ArrayApi", + "valueType": { + "$ref": "201" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.value", + "serializationOptions": { + "$id": "304", + "json": { + "$id": "305", + "name": "value" + } + } + }, + { + "$id": "306", + "kind": "property", + "name": "nextLink", + "serializedName": "nextLink", + "doc": "The link to the next page of items", + "type": { + "$id": "307", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "308", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.nextLink", + "serializationOptions": { + "$id": "309", + "json": { + "$id": "310", + "name": "nextLink" + } + } + } + ] + }, + { + "$id": "311", + "kind": "model", + "name": "PagedApiDefinition", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage", + "usage": "Output,Json", + "doc": "Paged collection of ApiDefinition items", + "decorators": [], + "properties": [ + { + "$id": "312", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The ApiDefinition items on this page", + "type": { + "$id": "313", + "kind": "array", + "name": "ArrayApiDefinition", + "valueType": { + "$ref": "164" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.value", + "serializationOptions": { + "$id": "314", + "json": { + "$id": "315", + "name": "value" + } + } + }, + { + "$id": "316", + "kind": "property", + "name": "nextLink", + "serializedName": "nextLink", + "doc": "The link to the next page of items", + "type": { + "$id": "317", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "318", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.nextLink", + "serializationOptions": { + "$id": "319", + "json": { + "$id": "320", + "name": "nextLink" + } + } + } + ] + }, + { + "$id": "321", + "kind": "model", + "name": "ResourceOperationStatusApiSpecExportResultApiSpecExportResultError", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus", + "usage": "Output,Json,LroInitial,LroPolling,LroFinalEnvelope", + "doc": "Provides status details for long running operations.", + "decorators": [], + "properties": [ + { + "$id": "322", + "kind": "property", + "name": "id", + "serializedName": "id", + "doc": "The unique ID of the operation.", + "type": { + "$id": "323", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.id", + "serializationOptions": { + "$id": "324", + "json": { + "$id": "325", + "name": "id" + } + } + }, + { + "$id": "326", + "kind": "property", + "name": "status", + "serializedName": "status", + "doc": "The status of the operation", + "type": { + "$ref": "50" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.status", + "serializationOptions": { + "$id": "327", + "json": { + "$id": "328", + "name": "status" + } + } + }, + { + "$id": "329", + "kind": "property", + "name": "error", + "serializedName": "error", + "doc": "Error object that describes the error when status is \"Failed\".", + "type": { + "$id": "330", + "kind": "model", + "name": "Error", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error", + "usage": "Output,Json,Exception,LroInitial,LroPolling,LroFinalEnvelope", + "doc": "The error object.", + "decorators": [], + "properties": [ + { + "$id": "331", + "kind": "property", + "name": "code", + "serializedName": "code", + "doc": "One of a server-defined set of error codes.", + "type": { + "$id": "332", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.code", + "serializationOptions": { + "$id": "333", + "json": { + "$id": "334", + "name": "code" + } + } + }, + { + "$id": "335", + "kind": "property", + "name": "message", + "serializedName": "message", + "doc": "A human-readable representation of the error.", + "type": { + "$id": "336", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.message", + "serializationOptions": { + "$id": "337", + "json": { + "$id": "338", + "name": "message" + } + } + }, + { + "$id": "339", + "kind": "property", + "name": "target", + "serializedName": "target", + "doc": "The target of the error.", + "type": { + "$id": "340", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.target", + "serializationOptions": { + "$id": "341", + "json": { + "$id": "342", + "name": "target" + } + } + }, + { + "$id": "343", + "kind": "property", + "name": "details", + "serializedName": "details", + "doc": "An array of details about specific errors that led to this reported error.", + "type": { + "$id": "344", + "kind": "array", + "name": "ArrayError", + "valueType": { + "$ref": "330" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.details", + "serializationOptions": { + "$id": "345", + "json": { + "$id": "346", + "name": "details" + } + } + }, + { + "$id": "347", + "kind": "property", + "name": "innererror", + "serializedName": "innererror", + "doc": "An object containing more specific information than the current object about the error.", + "type": { + "$id": "348", + "kind": "model", + "name": "InnerError", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.Foundations.InnerError", + "usage": "Output,Json,Exception,LroInitial,LroPolling,LroFinalEnvelope", + "doc": "An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses.", + "decorators": [], + "properties": [ + { + "$id": "349", + "kind": "property", + "name": "code", + "serializedName": "code", + "doc": "One of a server-defined set of error codes.", + "type": { + "$id": "350", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.InnerError.code", + "serializationOptions": { + "$id": "351", + "json": { + "$id": "352", + "name": "code" + } + } + }, + { + "$id": "353", + "kind": "property", + "name": "innererror", + "serializedName": "innererror", + "doc": "Inner error.", + "type": { + "$ref": "348" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.InnerError.innererror", + "serializationOptions": { + "$id": "354", + "json": { + "$id": "355", + "name": "innererror" + } + } + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.Error.innererror", + "serializationOptions": { + "$id": "356", + "json": { + "$id": "357", + "name": "innererror" + } + } + } + ] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.error", + "serializationOptions": { + "$id": "358", + "json": { + "$id": "359", + "name": "error" + } + } + }, + { + "$id": "360", + "kind": "property", + "name": "result", + "serializedName": "result", + "doc": "The result of the operation.", + "type": { + "$ref": "189" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.ResourceOperationStatus.result", + "serializationOptions": { + "$id": "361", + "json": { + "$id": "362", + "name": "result" + } + } + } + ] + }, + { + "$ref": "330" + }, + { + "$ref": "348" + }, + { + "$id": "363", + "kind": "model", + "name": "PagedApiDeployment", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage", + "usage": "Output,Json", + "doc": "Paged collection of ApiDeployment items", + "decorators": [], + "properties": [ + { + "$id": "364", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The ApiDeployment items on this page", + "type": { + "$id": "365", + "kind": "array", + "name": "ArrayApiDeployment", + "valueType": { + "$ref": "130" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.value", + "serializationOptions": { + "$id": "366", + "json": { + "$id": "367", + "name": "value" + } + } + }, + { + "$id": "368", + "kind": "property", + "name": "nextLink", + "serializedName": "nextLink", + "doc": "The link to the next page of items", + "type": { + "$id": "369", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "370", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.nextLink", + "serializationOptions": { + "$id": "371", + "json": { + "$id": "372", + "name": "nextLink" + } + } + } + ] + }, + { + "$id": "373", + "kind": "model", + "name": "PagedEnvironment", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage", + "usage": "Output,Json", + "doc": "Paged collection of Environment items", + "decorators": [], + "properties": [ + { + "$id": "374", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The Environment items on this page", + "type": { + "$id": "375", + "kind": "array", + "name": "ArrayEnvironment", + "valueType": { + "$ref": "74" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.value", + "serializationOptions": { + "$id": "376", + "json": { + "$id": "377", + "name": "value" + } + } + }, + { + "$id": "378", + "kind": "property", + "name": "nextLink", + "serializedName": "nextLink", + "doc": "The link to the next page of items", + "type": { + "$id": "379", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "380", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.nextLink", + "serializationOptions": { + "$id": "381", + "json": { + "$id": "382", + "name": "nextLink" + } + } + } + ] + }, + { + "$id": "383", + "kind": "model", + "name": "PagedApiVersion", + "namespace": "azure.ApiCenter", + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage", + "usage": "Output,Json", + "doc": "Paged collection of ApiVersion items", + "decorators": [], + "properties": [ + { + "$id": "384", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The ApiVersion items on this page", + "type": { + "$id": "385", + "kind": "array", + "name": "ArrayApiVersion", + "valueType": { + "$ref": "62" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.value", + "serializationOptions": { + "$id": "386", + "json": { + "$id": "387", + "name": "value" + } + } + }, + { + "$id": "388", + "kind": "property", + "name": "nextLink", + "serializedName": "nextLink", + "doc": "The link to the next page of items", + "type": { + "$id": "389", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "390", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "Azure.Core.Foundations.CustomPage.nextLink", + "serializationOptions": { + "$id": "391", + "json": { + "$id": "392", + "name": "nextLink" + } + } + } + ] + } + ], + "clients": [ + { + "$id": "393", + "kind": "client", + "name": "DataApiClient", + "namespace": "azure.ApiCenter", + "doc": "Data API introduces endpoints to manage your API Center resources.", + "operations": [], + "parameters": [], + "decorators": [ + { + "$id": "394", + "name": "TypeSpec.@service", + "arguments": { + "$id": "395", + "options": { + "$id": "396", + "title": "Azure API Center Data API" + } + } + } + ], + "crossLanguageDefinitionId": "ApiCenter.DataApi", + "apiVersions": [ + "2024-02-01-preview" + ], + "children": [ + { + "$id": "397", + "kind": "client", + "name": "Apis", + "namespace": "azure.ApiCenter", + "operations": [ + { + "$id": "398", + "name": "list", + "resourceName": "Api", + "doc": "List a collection of APIs.", + "accessibility": "public", + "parameters": [ + { + "$id": "399", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "400", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "401", + "type": { + "$id": "402", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "403", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "404", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "405", + "name": "top", + "nameInRequest": "top", + "doc": "The number of result items to return.", + "type": { + "$id": "406", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "407", + "name": "skip", + "nameInRequest": "skip", + "doc": "The number of result items to skip.", + "type": { + "$id": "408", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "409", + "name": "maxpagesize", + "nameInRequest": "maxpagesize", + "doc": "The maximum number of result items per page.", + "type": { + "$id": "410", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "411", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "412", + "kind": "constant", + "valueType": { + "$id": "413", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "414", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "301" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis", + "bufferResponse": true, + "paging": { + "$id": "415", + "itemPropertySegments": [ + "value" + ], + "nextLink": { + "$id": "416", + "responseSegments": [ + "nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.Apis.list", + "decorators": [], + "examples": [ + { + "$id": "417", + "kind": "http", + "name": "Apis_List", + "description": "Apis_List", + "filePath": "2024-02-01-preview/Apis_List.json", + "parameters": [ + { + "$id": "418", + "parameter": { + "$ref": "399" + }, + "value": { + "$id": "419", + "kind": "string", + "type": { + "$ref": "400" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "420", + "parameter": { + "$ref": "403" + }, + "value": { + "$id": "421", + "kind": "string", + "type": { + "$ref": "404" + }, + "value": "default" + } + } + ], + "responses": [ + { + "$id": "422", + "response": { + "$ref": "414" + }, + "statusCode": 200, + "bodyValue": { + "$id": "423", + "kind": "model", + "type": { + "$ref": "301" + }, + "value": { + "$id": "424", + "value": { + "$id": "425", + "kind": "array", + "type": { + "$ref": "303" + }, + "value": [ + { + "$id": "426", + "kind": "model", + "type": { + "$ref": "201" + }, + "value": { + "$id": "427", + "name": { + "$id": "428", + "kind": "string", + "type": { + "$ref": "203" + }, + "value": "echo-api" + }, + "title": { + "$id": "429", + "kind": "string", + "type": { + "$ref": "207" + }, + "value": "Echo API" + }, + "kind": { + "$id": "430", + "kind": "string", + "type": { + "$ref": "32" + }, + "value": "rest" + }, + "lastUpdated": { + "$id": "431", + "kind": "string", + "type": { + "$ref": "287" + }, + "value": "2023-12-18T18:49:11.878Z" + }, + "description": { + "$id": "432", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "A simple HTTP request/response service." + }, + "lifecycleStage": { + "$id": "433", + "kind": "string", + "type": { + "$ref": "2" + }, + "value": "design" + }, + "termsOfService": { + "$id": "434", + "kind": "model", + "type": { + "$ref": "225" + }, + "value": { + "$id": "435", + "url": { + "$id": "436", + "kind": "string", + "type": { + "$ref": "227" + }, + "value": "https://contoso.com/terms-of-service" + } + } + }, + "license": { + "$id": "437", + "kind": "model", + "type": { + "$ref": "233" + }, + "value": { + "$id": "438", + "name": { + "$id": "439", + "kind": "string", + "type": { + "$ref": "235" + }, + "value": "default" + }, + "url": { + "$id": "440", + "kind": "string", + "type": { + "$ref": "239" + }, + "value": "https://contoso.com/license" + } + } + }, + "externalDocumentation": { + "$id": "441", + "kind": "array", + "type": { + "$ref": "249" + }, + "value": [ + { + "$id": "442", + "kind": "model", + "type": { + "$ref": "250" + }, + "value": { + "$id": "443", + "title": { + "$id": "444", + "kind": "string", + "type": { + "$ref": "252" + }, + "value": "Onboarding docs" + }, + "description": { + "$id": "445", + "kind": "string", + "type": { + "$ref": "256" + }, + "value": "Learn how to onboard to the Echo API." + }, + "url": { + "$id": "446", + "kind": "string", + "type": { + "$ref": "260" + }, + "value": "https://docs.contoso.com" + } + } + } + ] + }, + "contacts": { + "$id": "447", + "kind": "array", + "type": { + "$ref": "266" + }, + "value": [ + { + "$id": "448", + "kind": "model", + "type": { + "$ref": "267" + }, + "value": { + "$id": "449", + "name": { + "$id": "450", + "kind": "string", + "type": { + "$ref": "269" + }, + "value": "Contoso support" + }, + "url": { + "$id": "451", + "kind": "string", + "type": { + "$ref": "273" + }, + "value": "https://support.contoso.com" + }, + "email": { + "$id": "452", + "kind": "string", + "type": { + "$ref": "277" + }, + "value": "support@contoso.com" + } + } + } + ] + } + } + } + ] + }, + "nextLink": { + "$id": "453", + "kind": "string", + "type": { + "$ref": "307" + }, + "value": "https://..." + } + } + } + } + ] + } + ] + }, + { + "$id": "454", + "name": "listAll", + "resourceName": "Apis", + "doc": "List a collection of APIs across workspaces.", + "accessibility": "public", + "parameters": [ + { + "$id": "455", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "456", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "457", + "type": { + "$id": "458", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "459", + "name": "top", + "nameInRequest": "top", + "doc": "The number of result items to return.", + "type": { + "$id": "460", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "461", + "name": "skip", + "nameInRequest": "skip", + "doc": "The number of result items to skip.", + "type": { + "$id": "462", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "463", + "name": "maxpagesize", + "nameInRequest": "maxpagesize", + "doc": "The maximum number of result items per page.", + "type": { + "$id": "464", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "465", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "466", + "kind": "constant", + "valueType": { + "$id": "467", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "468", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "291" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/apis", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.Apis.listAll", + "decorators": [], + "examples": [ + { + "$id": "469", + "kind": "http", + "name": "Apis_ListAll", + "description": "Apis_ListAll", + "filePath": "2024-02-01-preview/Apis_ListAll.json", + "parameters": [ + { + "$id": "470", + "parameter": { + "$ref": "455" + }, + "value": { + "$id": "471", + "kind": "string", + "type": { + "$ref": "456" + }, + "value": "2024-02-01-preview" + } + } + ], + "responses": [ + { + "$id": "472", + "response": { + "$ref": "468" + }, + "statusCode": 200, + "bodyValue": { + "$id": "473", + "kind": "model", + "type": { + "$ref": "291" + }, + "value": { + "$id": "474", + "value": { + "$id": "475", + "kind": "array", + "type": { + "$ref": "293" + }, + "value": [ + { + "$id": "476", + "kind": "model", + "type": { + "$ref": "201" + }, + "value": { + "$id": "477", + "name": { + "$id": "478", + "kind": "string", + "type": { + "$ref": "203" + }, + "value": "echo-api" + }, + "title": { + "$id": "479", + "kind": "string", + "type": { + "$ref": "207" + }, + "value": "Echo API" + }, + "kind": { + "$id": "480", + "kind": "string", + "type": { + "$ref": "32" + }, + "value": "rest" + }, + "lastUpdated": { + "$id": "481", + "kind": "string", + "type": { + "$ref": "287" + }, + "value": "2023-12-18T18:49:11.878Z" + }, + "description": { + "$id": "482", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "A simple HTTP request/response service." + }, + "lifecycleStage": { + "$id": "483", + "kind": "string", + "type": { + "$ref": "2" + }, + "value": "design" + }, + "termsOfService": { + "$id": "484", + "kind": "model", + "type": { + "$ref": "225" + }, + "value": { + "$id": "485", + "url": { + "$id": "486", + "kind": "string", + "type": { + "$ref": "227" + }, + "value": "https://contoso.com/terms-of-service" + } + } + }, + "license": { + "$id": "487", + "kind": "model", + "type": { + "$ref": "233" + }, + "value": { + "$id": "488", + "name": { + "$id": "489", + "kind": "string", + "type": { + "$ref": "235" + }, + "value": "default" + }, + "url": { + "$id": "490", + "kind": "string", + "type": { + "$ref": "239" + }, + "value": "https://contoso.com/license" + } + } + }, + "externalDocumentation": { + "$id": "491", + "kind": "array", + "type": { + "$ref": "249" + }, + "value": [ + { + "$id": "492", + "kind": "model", + "type": { + "$ref": "250" + }, + "value": { + "$id": "493", + "title": { + "$id": "494", + "kind": "string", + "type": { + "$ref": "252" + }, + "value": "Onboarding docs" + }, + "description": { + "$id": "495", + "kind": "string", + "type": { + "$ref": "256" + }, + "value": "Learn how to onboard to the Echo API." + }, + "url": { + "$id": "496", + "kind": "string", + "type": { + "$ref": "260" + }, + "value": "https://docs.contoso.com" + } + } + } + ] + }, + "contacts": { + "$id": "497", + "kind": "array", + "type": { + "$ref": "266" + }, + "value": [ + { + "$id": "498", + "kind": "model", + "type": { + "$ref": "267" + }, + "value": { + "$id": "499", + "name": { + "$id": "500", + "kind": "string", + "type": { + "$ref": "269" + }, + "value": "Contoso support" + }, + "url": { + "$id": "501", + "kind": "string", + "type": { + "$ref": "273" + }, + "value": "https://support.contoso.com" + }, + "email": { + "$id": "502", + "kind": "string", + "type": { + "$ref": "277" + }, + "value": "support@contoso.com" + } + } + } + ] + } + } + } + ] + }, + "nextLink": { + "$id": "503", + "kind": "string", + "type": { + "$ref": "297" + }, + "value": "https://microsoft.com/a" + } + } + } + } + ] + } + ] + }, + { + "$id": "504", + "name": "get", + "resourceName": "Api", + "doc": "Get an API.", + "accessibility": "public", + "parameters": [ + { + "$id": "505", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "506", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "507", + "type": { + "$id": "508", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "509", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "510", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "511", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "512", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "513", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "514", + "kind": "constant", + "valueType": { + "$id": "515", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "516", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "201" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.Apis.get", + "decorators": [], + "examples": [ + { + "$id": "517", + "kind": "http", + "name": "Apis_Get", + "description": "Apis_Get", + "filePath": "2024-02-01-preview/Apis_Get.json", + "parameters": [ + { + "$id": "518", + "parameter": { + "$ref": "505" + }, + "value": { + "$id": "519", + "kind": "string", + "type": { + "$ref": "506" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "520", + "parameter": { + "$ref": "509" + }, + "value": { + "$id": "521", + "kind": "string", + "type": { + "$ref": "510" + }, + "value": "default" + } + }, + { + "$id": "522", + "parameter": { + "$ref": "511" + }, + "value": { + "$id": "523", + "kind": "string", + "type": { + "$ref": "512" + }, + "value": "echo-api" + } + } + ], + "responses": [ + { + "$id": "524", + "response": { + "$ref": "516" + }, + "statusCode": 200, + "bodyValue": { + "$id": "525", + "kind": "model", + "type": { + "$ref": "201" + }, + "value": { + "$id": "526", + "name": { + "$id": "527", + "kind": "string", + "type": { + "$ref": "203" + }, + "value": "echo-api" + }, + "title": { + "$id": "528", + "kind": "string", + "type": { + "$ref": "207" + }, + "value": "Echo API" + }, + "kind": { + "$id": "529", + "kind": "string", + "type": { + "$ref": "32" + }, + "value": "rest" + }, + "lastUpdated": { + "$id": "530", + "kind": "string", + "type": { + "$ref": "287" + }, + "value": "2023-12-18T18:49:11.878Z" + }, + "description": { + "$id": "531", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "A simple HTTP request/response service." + }, + "lifecycleStage": { + "$id": "532", + "kind": "string", + "type": { + "$ref": "2" + }, + "value": "design" + }, + "termsOfService": { + "$id": "533", + "kind": "model", + "type": { + "$ref": "225" + }, + "value": { + "$id": "534", + "url": { + "$id": "535", + "kind": "string", + "type": { + "$ref": "227" + }, + "value": "https://contoso.com/terms-of-service" + } + } + }, + "license": { + "$id": "536", + "kind": "model", + "type": { + "$ref": "233" + }, + "value": { + "$id": "537", + "name": { + "$id": "538", + "kind": "string", + "type": { + "$ref": "235" + }, + "value": "default" + }, + "url": { + "$id": "539", + "kind": "string", + "type": { + "$ref": "239" + }, + "value": "https://contoso.com/license" + } + } + }, + "externalDocumentation": { + "$id": "540", + "kind": "array", + "type": { + "$ref": "249" + }, + "value": [ + { + "$id": "541", + "kind": "model", + "type": { + "$ref": "250" + }, + "value": { + "$id": "542", + "title": { + "$id": "543", + "kind": "string", + "type": { + "$ref": "252" + }, + "value": "Onboarding docs" + }, + "description": { + "$id": "544", + "kind": "string", + "type": { + "$ref": "256" + }, + "value": "Learn how to onboard to the Echo API." + }, + "url": { + "$id": "545", + "kind": "string", + "type": { + "$ref": "260" + }, + "value": "https://docs.contoso.com" + } + } + } + ] + }, + "contacts": { + "$id": "546", + "kind": "array", + "type": { + "$ref": "266" + }, + "value": [ + { + "$id": "547", + "kind": "model", + "type": { + "$ref": "267" + }, + "value": { + "$id": "548", + "name": { + "$id": "549", + "kind": "string", + "type": { + "$ref": "269" + }, + "value": "Contoso support" + }, + "url": { + "$id": "550", + "kind": "string", + "type": { + "$ref": "273" + }, + "value": "https://support.contoso.com" + }, + "email": { + "$id": "551", + "kind": "string", + "type": { + "$ref": "277" + }, + "value": "support@contoso.com" + } + } + } + ] + } + } + } + } + ] + } + ] + } + ], + "parameters": [], + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Apis", + "apiVersions": [ + "2024-02-01-preview" + ], + "parent": { + "$ref": "393" + } + }, + { + "$id": "552", + "kind": "client", + "name": "ApiDefinitions", + "namespace": "azure.ApiCenter", + "operations": [ + { + "$id": "553", + "name": "listDefinitions", + "resourceName": "ApiDefinition", + "doc": "List a collection of API definitions.", + "accessibility": "public", + "parameters": [ + { + "$id": "554", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "555", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "556", + "type": { + "$id": "557", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "558", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "559", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "560", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "561", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "562", + "name": "versionName", + "nameInRequest": "versionName", + "doc": "Version identifier.", + "type": { + "$id": "563", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "564", + "name": "top", + "nameInRequest": "top", + "doc": "The number of result items to return.", + "type": { + "$id": "565", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "566", + "name": "skip", + "nameInRequest": "skip", + "doc": "The number of result items to skip.", + "type": { + "$id": "567", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "568", + "name": "maxpagesize", + "nameInRequest": "maxpagesize", + "doc": "The maximum number of result items per page.", + "type": { + "$id": "569", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "570", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "571", + "kind": "constant", + "valueType": { + "$id": "572", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "573", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "311" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions", + "bufferResponse": true, + "paging": { + "$id": "574", + "itemPropertySegments": [ + "value" + ], + "nextLink": { + "$id": "575", + "responseSegments": [ + "nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinitions.listDefinitions", + "decorators": [], + "examples": [ + { + "$id": "576", + "kind": "http", + "name": "ApiDefinitions_ListDefinitions", + "description": "ApiDefinitions_ListDefinitions", + "filePath": "2024-02-01-preview/ApiDefinitions_ListDefinitions.json", + "parameters": [ + { + "$id": "577", + "parameter": { + "$ref": "554" + }, + "value": { + "$id": "578", + "kind": "string", + "type": { + "$ref": "555" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "579", + "parameter": { + "$ref": "558" + }, + "value": { + "$id": "580", + "kind": "string", + "type": { + "$ref": "559" + }, + "value": "default" + } + }, + { + "$id": "581", + "parameter": { + "$ref": "560" + }, + "value": { + "$id": "582", + "kind": "string", + "type": { + "$ref": "561" + }, + "value": "echo-api" + } + }, + { + "$id": "583", + "parameter": { + "$ref": "562" + }, + "value": { + "$id": "584", + "kind": "string", + "type": { + "$ref": "563" + }, + "value": "2023-01-01" + } + } + ], + "responses": [ + { + "$id": "585", + "response": { + "$ref": "573" + }, + "statusCode": 200, + "bodyValue": { + "$id": "586", + "kind": "model", + "type": { + "$ref": "311" + }, + "value": { + "$id": "587", + "value": { + "$id": "588", + "kind": "array", + "type": { + "$ref": "313" + }, + "value": [ + { + "$id": "589", + "kind": "model", + "type": { + "$ref": "164" + }, + "value": { + "$id": "590", + "name": { + "$id": "591", + "kind": "string", + "type": { + "$ref": "166" + }, + "value": "default" + }, + "title": { + "$id": "592", + "kind": "string", + "type": { + "$ref": "170" + }, + "value": "Default" + }, + "specification": { + "$id": "593", + "kind": "model", + "type": { + "$ref": "178" + }, + "value": { + "$id": "594", + "name": { + "$id": "595", + "kind": "string", + "type": { + "$ref": "180" + }, + "value": "openapi" + }, + "version": { + "$id": "596", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "3.0.1" + } + } + }, + "description": { + "$id": "597", + "kind": "string", + "type": { + "$ref": "174" + }, + "value": "Default API definition." + } + } + } + ] + }, + "nextLink": { + "$id": "598", + "kind": "string", + "type": { + "$ref": "317" + }, + "value": "https://..." + } + } + } + } + ] + } + ] + }, + { + "$id": "599", + "name": "getDefinition", + "resourceName": "ApiDefinition", + "doc": "Get an API definition.", + "accessibility": "public", + "parameters": [ + { + "$id": "600", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "601", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "602", + "type": { + "$id": "603", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "604", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "605", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "606", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "607", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "608", + "name": "versionName", + "nameInRequest": "versionName", + "doc": "Version identifier.", + "type": { + "$id": "609", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "610", + "name": "definitionName", + "nameInRequest": "definitionName", + "doc": "Definition identifier.", + "type": { + "$id": "611", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "612", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "613", + "kind": "constant", + "valueType": { + "$id": "614", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "615", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "164" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinitions.getDefinition", + "decorators": [], + "examples": [ + { + "$id": "616", + "kind": "http", + "name": "ApiDefinitions_GetDefinition", + "description": "ApiDefinitions_GetDefinition", + "filePath": "2024-02-01-preview/ApiDefinitions_GetDefinition.json", + "parameters": [ + { + "$id": "617", + "parameter": { + "$ref": "600" + }, + "value": { + "$id": "618", + "kind": "string", + "type": { + "$ref": "601" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "619", + "parameter": { + "$ref": "604" + }, + "value": { + "$id": "620", + "kind": "string", + "type": { + "$ref": "605" + }, + "value": "default" + } + }, + { + "$id": "621", + "parameter": { + "$ref": "606" + }, + "value": { + "$id": "622", + "kind": "string", + "type": { + "$ref": "607" + }, + "value": "echo-api" + } + }, + { + "$id": "623", + "parameter": { + "$ref": "608" + }, + "value": { + "$id": "624", + "kind": "string", + "type": { + "$ref": "609" + }, + "value": "2023-01-01" + } + }, + { + "$id": "625", + "parameter": { + "$ref": "610" + }, + "value": { + "$id": "626", + "kind": "string", + "type": { + "$ref": "611" + }, + "value": "default" + } + } + ], + "responses": [ + { + "$id": "627", + "response": { + "$ref": "615" + }, + "statusCode": 200, + "bodyValue": { + "$id": "628", + "kind": "model", + "type": { + "$ref": "164" + }, + "value": { + "$id": "629", + "name": { + "$id": "630", + "kind": "string", + "type": { + "$ref": "166" + }, + "value": "default" + }, + "title": { + "$id": "631", + "kind": "string", + "type": { + "$ref": "170" + }, + "value": "Default" + }, + "specification": { + "$id": "632", + "kind": "model", + "type": { + "$ref": "178" + }, + "value": { + "$id": "633", + "name": { + "$id": "634", + "kind": "string", + "type": { + "$ref": "180" + }, + "value": "openapi" + }, + "version": { + "$id": "635", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "3.0.1" + } + } + }, + "description": { + "$id": "636", + "kind": "string", + "type": { + "$ref": "174" + }, + "value": "Default API definition." + } + } + } + } + ] + } + ] + }, + { + "$id": "637", + "name": "getExportSpecificationOperationStatus", + "resourceName": "ResourceOperationStatus", + "doc": "Gets status of a an API specification export operation.", + "accessibility": "public", + "parameters": [ + { + "$id": "638", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "639", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "640", + "type": { + "$id": "641", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "642", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "643", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "644", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "645", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "646", + "name": "versionName", + "nameInRequest": "versionName", + "doc": "Version identifier.", + "type": { + "$id": "647", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "648", + "name": "definitionName", + "nameInRequest": "definitionName", + "doc": "API definition identifier.", + "type": { + "$id": "649", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "650", + "name": "operationId", + "nameInRequest": "operationId", + "doc": "The unique ID of the operation.", + "type": { + "$id": "651", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "652", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "653", + "kind": "constant", + "valueType": { + "$id": "654", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "655", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "321" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}/operations/{operationId}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinitions.getExportSpecificationOperationStatus", + "decorators": [], + "examples": [ + { + "$id": "656", + "kind": "http", + "name": "ApiDefinitions_GetExportSpecificationOperationStatus", + "description": "ApiDefinitions_GetExportSpecificationOperationStatus", + "filePath": "2024-02-01-preview/ApiDefinitions_GetExportSpecificationOperationStatus.json", + "parameters": [ + { + "$id": "657", + "parameter": { + "$ref": "638" + }, + "value": { + "$id": "658", + "kind": "string", + "type": { + "$ref": "639" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "659", + "parameter": { + "$ref": "642" + }, + "value": { + "$id": "660", + "kind": "string", + "type": { + "$ref": "643" + }, + "value": "default" + } + }, + { + "$id": "661", + "parameter": { + "$ref": "644" + }, + "value": { + "$id": "662", + "kind": "string", + "type": { + "$ref": "645" + }, + "value": "echo-api" + } + }, + { + "$id": "663", + "parameter": { + "$ref": "646" + }, + "value": { + "$id": "664", + "kind": "string", + "type": { + "$ref": "647" + }, + "value": "2023-01-01" + } + }, + { + "$id": "665", + "parameter": { + "$ref": "648" + }, + "value": { + "$id": "666", + "kind": "string", + "type": { + "$ref": "649" + }, + "value": "default" + } + }, + { + "$id": "667", + "parameter": { + "$ref": "650" + }, + "value": { + "$id": "668", + "kind": "string", + "type": { + "$ref": "651" + }, + "value": "00000000-0000-0000-0000-000000000001" + } + } + ], + "responses": [ + { + "$id": "669", + "response": { + "$ref": "655" + }, + "statusCode": 200, + "bodyValue": { + "$id": "670", + "kind": "model", + "type": { + "$ref": "321" + }, + "value": { + "$id": "671", + "status": { + "$id": "672", + "kind": "string", + "type": { + "$ref": "50" + }, + "value": "Succeeded" + }, + "result": { + "$id": "673", + "kind": "model", + "type": { + "$ref": "189" + }, + "value": { + "$id": "674", + "value": { + "$id": "675", + "kind": "string", + "type": { + "$ref": "195" + }, + "value": "{ ... }" + }, + "format": { + "$id": "676", + "kind": "string", + "type": { + "$ref": "28" + }, + "value": "link" + } + } + } + } + } + } + ] + } + ] + }, + { + "$id": "677", + "name": "exportSpecification", + "resourceName": "ApiDefinitions", + "doc": "Export an API specification asynchronously.", + "accessibility": "public", + "parameters": [ + { + "$id": "678", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "679", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "680", + "type": { + "$id": "681", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "682", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "683", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "684", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "685", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "686", + "name": "versionName", + "nameInRequest": "versionName", + "doc": "Version identifier.", + "type": { + "$id": "687", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "688", + "name": "definitionName", + "nameInRequest": "definitionName", + "doc": "API definition identifier.", + "type": { + "$id": "689", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "690", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "691", + "kind": "constant", + "valueType": { + "$id": "692", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "693", + "statusCodes": [ + 202 + ], + "bodyType": { + "$ref": "321" + }, + "headers": [ + { + "$id": "694", + "name": "operationLocation", + "nameInResponse": "Operation-Location", + "doc": "The location for monitoring the operation state.", + "type": { + "$id": "695", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "696", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "POST", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}:exportSpecification", + "bufferResponse": true, + "longRunning": { + "$id": "697", + "finalStateVia": 3, + "finalResponse": { + "$id": "698", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "321" + } + }, + "resultPath": "result" + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinitions.exportSpecification", + "decorators": [], + "examples": [ + { + "$id": "699", + "kind": "http", + "name": "ApiDefinitions_ExportSpecification", + "description": "ApiDefinitions_ExportSpecification", + "filePath": "2024-02-01-preview/ApiDefinitions_ExportSpecification.json", + "parameters": [ + { + "$id": "700", + "parameter": { + "$ref": "678" + }, + "value": { + "$id": "701", + "kind": "string", + "type": { + "$ref": "679" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "702", + "parameter": { + "$ref": "682" + }, + "value": { + "$id": "703", + "kind": "string", + "type": { + "$ref": "683" + }, + "value": "default" + } + }, + { + "$id": "704", + "parameter": { + "$ref": "684" + }, + "value": { + "$id": "705", + "kind": "string", + "type": { + "$ref": "685" + }, + "value": "echo-api" + } + }, + { + "$id": "706", + "parameter": { + "$ref": "686" + }, + "value": { + "$id": "707", + "kind": "string", + "type": { + "$ref": "687" + }, + "value": "2023-01-01" + } + }, + { + "$id": "708", + "parameter": { + "$ref": "688" + }, + "value": { + "$id": "709", + "kind": "string", + "type": { + "$ref": "689" + }, + "value": "default" + } + } + ], + "responses": [ + { + "$id": "710", + "response": { + "$ref": "693" + }, + "statusCode": 202, + "bodyValue": { + "$id": "711", + "kind": "model", + "type": { + "$ref": "321" + }, + "value": { + "$id": "712", + "status": { + "$id": "713", + "kind": "string", + "type": { + "$ref": "50" + }, + "value": "Succeeded" + }, + "result": { + "$id": "714", + "kind": "model", + "type": { + "$ref": "189" + }, + "value": { + "$id": "715", + "value": { + "$id": "716", + "kind": "string", + "type": { + "$ref": "195" + }, + "value": "{ ... }" + }, + "format": { + "$id": "717", + "kind": "string", + "type": { + "$ref": "28" + }, + "value": "link" + } + } + } + } + } + } + ] + } + ] + } + ], + "parameters": [], + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDefinitions", + "apiVersions": [ + "2024-02-01-preview" + ], + "parent": { + "$ref": "393" + } + }, + { + "$id": "718", + "kind": "client", + "name": "ApiDeployments", + "namespace": "azure.ApiCenter", + "operations": [ + { + "$id": "719", + "name": "listDeployments", + "resourceName": "ApiDeployment", + "doc": "List a collection of API deployments.", + "accessibility": "public", + "parameters": [ + { + "$id": "720", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "721", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "722", + "type": { + "$id": "723", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "724", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "725", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "726", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "727", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "728", + "name": "top", + "nameInRequest": "top", + "doc": "The number of result items to return.", + "type": { + "$id": "729", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "730", + "name": "skip", + "nameInRequest": "skip", + "doc": "The number of result items to skip.", + "type": { + "$id": "731", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "732", + "name": "maxpagesize", + "nameInRequest": "maxpagesize", + "doc": "The maximum number of result items per page.", + "type": { + "$id": "733", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "734", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "735", + "kind": "constant", + "valueType": { + "$id": "736", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "737", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "363" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/deployments", + "bufferResponse": true, + "paging": { + "$id": "738", + "itemPropertySegments": [ + "value" + ], + "nextLink": { + "$id": "739", + "responseSegments": [ + "nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployments.listDeployments", + "decorators": [], + "examples": [ + { + "$id": "740", + "kind": "http", + "name": "ApiDeployments_ListDeployments", + "description": "ApiDeployments_ListDeployments", + "filePath": "2024-02-01-preview/ApiDeployments_ListDeployments.json", + "parameters": [ + { + "$id": "741", + "parameter": { + "$ref": "720" + }, + "value": { + "$id": "742", + "kind": "string", + "type": { + "$ref": "721" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "743", + "parameter": { + "$ref": "724" + }, + "value": { + "$id": "744", + "kind": "string", + "type": { + "$ref": "725" + }, + "value": "default" + } + }, + { + "$id": "745", + "parameter": { + "$ref": "726" + }, + "value": { + "$id": "746", + "kind": "string", + "type": { + "$ref": "727" + }, + "value": "echo-api" + } + } + ], + "responses": [ + { + "$id": "747", + "response": { + "$ref": "737" + }, + "statusCode": 200, + "bodyValue": { + "$id": "748", + "kind": "model", + "type": { + "$ref": "363" + }, + "value": { + "$id": "749", + "value": { + "$id": "750", + "kind": "array", + "type": { + "$ref": "365" + }, + "value": [ + { + "$id": "751", + "kind": "model", + "type": { + "$ref": "130" + }, + "value": { + "$id": "752", + "name": { + "$id": "753", + "kind": "string", + "type": { + "$ref": "132" + }, + "value": "production" + }, + "title": { + "$id": "754", + "kind": "string", + "type": { + "$ref": "136" + }, + "value": "Production" + }, + "description": { + "$id": "755", + "kind": "string", + "type": { + "$ref": "140" + }, + "value": "Production deployment (Public Cloud)" + }, + "environment": { + "$id": "756", + "kind": "string", + "type": { + "$ref": "144" + }, + "value": "public" + }, + "server": { + "$id": "757", + "kind": "model", + "type": { + "$ref": "148" + }, + "value": { + "$id": "758", + "runtimeUris": { + "$id": "759", + "kind": "array", + "type": { + "$ref": "150" + }, + "value": [ + { + "$id": "760", + "kind": "string", + "type": { + "$ref": "151" + }, + "value": "https://contoso.azure-api.net" + } + ] + } + } + }, + "recommended": { + "$id": "761", + "kind": "boolean", + "type": { + "$ref": "161" + }, + "value": true + } + } + } + ] + }, + "nextLink": { + "$id": "762", + "kind": "string", + "type": { + "$ref": "369" + }, + "value": "https://microsoft.com/aiofpisa" + } + } + } + } + ] + } + ] + }, + { + "$id": "763", + "name": "getDeployment", + "resourceName": "ApiDeployment", + "doc": "Get an API deployment.", + "accessibility": "public", + "parameters": [ + { + "$id": "764", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "765", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "766", + "type": { + "$id": "767", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "768", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "769", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "770", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "771", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "772", + "name": "deploymentName", + "nameInRequest": "deploymentName", + "doc": "Deployment identifier.", + "type": { + "$id": "773", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "774", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "775", + "kind": "constant", + "valueType": { + "$id": "776", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "777", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "130" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/deployments/{deploymentName}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployments.getDeployment", + "decorators": [], + "examples": [ + { + "$id": "778", + "kind": "http", + "name": "ApiDeployments_GetDeployment", + "description": "ApiDeployments_GetDeployment", + "filePath": "2024-02-01-preview/ApiDeployments_GetDeployment.json", + "parameters": [ + { + "$id": "779", + "parameter": { + "$ref": "764" + }, + "value": { + "$id": "780", + "kind": "string", + "type": { + "$ref": "765" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "781", + "parameter": { + "$ref": "768" + }, + "value": { + "$id": "782", + "kind": "string", + "type": { + "$ref": "769" + }, + "value": "eeoezynpqqgtykbukjcelrwvomtccvbjwntxfqh" + } + }, + { + "$id": "783", + "parameter": { + "$ref": "770" + }, + "value": { + "$id": "784", + "kind": "string", + "type": { + "$ref": "771" + }, + "value": "lauuo" + } + }, + { + "$id": "785", + "parameter": { + "$ref": "772" + }, + "value": { + "$id": "786", + "kind": "string", + "type": { + "$ref": "773" + }, + "value": "ffc" + } + } + ], + "responses": [ + { + "$id": "787", + "response": { + "$ref": "777" + }, + "statusCode": 200, + "bodyValue": { + "$id": "788", + "kind": "model", + "type": { + "$ref": "130" + }, + "value": { + "$id": "789", + "name": { + "$id": "790", + "kind": "string", + "type": { + "$ref": "132" + }, + "value": "production" + }, + "title": { + "$id": "791", + "kind": "string", + "type": { + "$ref": "136" + }, + "value": "Production" + }, + "description": { + "$id": "792", + "kind": "string", + "type": { + "$ref": "140" + }, + "value": "Production deployment (Public Cloud)" + }, + "environment": { + "$id": "793", + "kind": "string", + "type": { + "$ref": "144" + }, + "value": "public" + }, + "server": { + "$id": "794", + "kind": "model", + "type": { + "$ref": "148" + }, + "value": { + "$id": "795", + "runtimeUris": { + "$id": "796", + "kind": "array", + "type": { + "$ref": "150" + }, + "value": [ + { + "$id": "797", + "kind": "string", + "type": { + "$ref": "151" + }, + "value": "https://contoso.azure-api.net" + } + ] + } + } + }, + "recommended": { + "$id": "798", + "kind": "boolean", + "type": { + "$ref": "161" + }, + "value": true + } + } + } + } + ] + } + ] + } + ], + "parameters": [], + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiDeployments", + "apiVersions": [ + "2024-02-01-preview" + ], + "parent": { + "$ref": "393" + } + }, + { + "$id": "799", + "kind": "client", + "name": "Environments", + "namespace": "azure.ApiCenter", + "operations": [ + { + "$id": "800", + "name": "list", + "resourceName": "Environment", + "doc": "List a collection of environments.", + "accessibility": "public", + "parameters": [ + { + "$id": "801", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "802", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "803", + "type": { + "$id": "804", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "805", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "806", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "807", + "name": "top", + "nameInRequest": "top", + "doc": "The number of result items to return.", + "type": { + "$id": "808", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "809", + "name": "skip", + "nameInRequest": "skip", + "doc": "The number of result items to skip.", + "type": { + "$id": "810", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "811", + "name": "maxpagesize", + "nameInRequest": "maxpagesize", + "doc": "The maximum number of result items per page.", + "type": { + "$id": "812", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "813", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "814", + "kind": "constant", + "valueType": { + "$id": "815", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "816", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "373" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/environments", + "bufferResponse": true, + "paging": { + "$id": "817", + "itemPropertySegments": [ + "value" + ], + "nextLink": { + "$id": "818", + "responseSegments": [ + "nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environments.list", + "decorators": [], + "examples": [ + { + "$id": "819", + "kind": "http", + "name": "Environments_List", + "description": "Environments_List", + "filePath": "2024-02-01-preview/Environments_List.json", + "parameters": [ + { + "$id": "820", + "parameter": { + "$ref": "801" + }, + "value": { + "$id": "821", + "kind": "string", + "type": { + "$ref": "802" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "822", + "parameter": { + "$ref": "805" + }, + "value": { + "$id": "823", + "kind": "string", + "type": { + "$ref": "806" + }, + "value": "default" + } + } + ], + "responses": [ + { + "$id": "824", + "response": { + "$ref": "816" + }, + "statusCode": 200, + "bodyValue": { + "$id": "825", + "kind": "model", + "type": { + "$ref": "373" + }, + "value": { + "$id": "826", + "value": { + "$id": "827", + "kind": "array", + "type": { + "$ref": "375" + }, + "value": [ + { + "$id": "828", + "kind": "model", + "type": { + "$ref": "74" + }, + "value": { + "$id": "829", + "name": { + "$id": "830", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "public" + }, + "title": { + "$id": "831", + "kind": "string", + "type": { + "$ref": "80" + }, + "value": "Public" + }, + "description": { + "$id": "832", + "kind": "string", + "type": { + "$ref": "87" + }, + "value": "Public Cloud environment." + }, + "kind": { + "$id": "833", + "kind": "string", + "type": { + "$ref": "18" + }, + "value": "production" + }, + "server": { + "$id": "834", + "kind": "model", + "type": { + "$ref": "91" + }, + "value": { + "$id": "835", + "type": { + "$id": "836", + "kind": "string", + "type": { + "$ref": "93" + }, + "value": "Azure API Management" + }, + "managementPortalUris": { + "$id": "837", + "kind": "array", + "type": { + "$ref": "97" + }, + "value": [ + { + "$id": "838", + "kind": "string", + "type": { + "$ref": "98" + }, + "value": "https://portal.azure.com" + } + ] + } + } + }, + "onboarding": { + "$id": "839", + "kind": "model", + "type": { + "$ref": "104" + }, + "value": { + "$id": "840", + "instructions": { + "$id": "841", + "kind": "string", + "type": { + "$ref": "106" + }, + "value": "https://aka.ms/apim-devportal" + }, + "developerPortalUris": { + "$id": "842", + "kind": "array", + "type": { + "$ref": "110" + }, + "value": [ + { + "$id": "843", + "kind": "string", + "type": { + "$ref": "111" + }, + "value": "https://contoso.developer.azure-api.net" + } + ] + } + } + } + } + } + ] + }, + "nextLink": { + "$id": "844", + "kind": "string", + "type": { + "$ref": "379" + }, + "value": "https://..." + } + } + } + } + ] + } + ] + }, + { + "$id": "845", + "name": "listAll", + "resourceName": "Environments", + "doc": "List a collection of environments across workspaces.", + "accessibility": "public", + "parameters": [ + { + "$id": "846", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "847", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "848", + "type": { + "$id": "849", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "850", + "name": "top", + "nameInRequest": "top", + "doc": "The number of result items to return.", + "type": { + "$id": "851", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "852", + "name": "skip", + "nameInRequest": "skip", + "doc": "The number of result items to skip.", + "type": { + "$id": "853", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "854", + "name": "maxpagesize", + "nameInRequest": "maxpagesize", + "doc": "The maximum number of result items per page.", + "type": { + "$id": "855", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "856", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "857", + "kind": "constant", + "valueType": { + "$id": "858", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "859", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "120" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/environments", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environments.listAll", + "decorators": [], + "examples": [ + { + "$id": "860", + "kind": "http", + "name": "Environments_ListAll", + "description": "Environments_ListAll", + "filePath": "2024-02-01-preview/Environments_ListAll.json", + "parameters": [ + { + "$id": "861", + "parameter": { + "$ref": "846" + }, + "value": { + "$id": "862", + "kind": "string", + "type": { + "$ref": "847" + }, + "value": "2024-02-01-preview" + } + } + ], + "responses": [ + { + "$id": "863", + "response": { + "$ref": "859" + }, + "statusCode": 200, + "bodyValue": { + "$id": "864", + "kind": "model", + "type": { + "$ref": "120" + }, + "value": { + "$id": "865", + "value": { + "$id": "866", + "kind": "array", + "type": { + "$ref": "122" + }, + "value": [ + { + "$id": "867", + "kind": "model", + "type": { + "$ref": "74" + }, + "value": { + "$id": "868", + "name": { + "$id": "869", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "public" + }, + "title": { + "$id": "870", + "kind": "string", + "type": { + "$ref": "80" + }, + "value": "Public" + }, + "description": { + "$id": "871", + "kind": "string", + "type": { + "$ref": "87" + }, + "value": "Public Cloud environment." + }, + "kind": { + "$id": "872", + "kind": "string", + "type": { + "$ref": "18" + }, + "value": "production" + }, + "server": { + "$id": "873", + "kind": "model", + "type": { + "$ref": "91" + }, + "value": { + "$id": "874", + "type": { + "$id": "875", + "kind": "string", + "type": { + "$ref": "93" + }, + "value": "Azure API Management" + }, + "managementPortalUris": { + "$id": "876", + "kind": "array", + "type": { + "$ref": "97" + }, + "value": [ + { + "$id": "877", + "kind": "string", + "type": { + "$ref": "98" + }, + "value": "https://portal.azure.com" + } + ] + } + } + }, + "onboarding": { + "$id": "878", + "kind": "model", + "type": { + "$ref": "104" + }, + "value": { + "$id": "879", + "instructions": { + "$id": "880", + "kind": "string", + "type": { + "$ref": "106" + }, + "value": "https://aka.ms/apim-devportal" + }, + "developerPortalUris": { + "$id": "881", + "kind": "array", + "type": { + "$ref": "110" + }, + "value": [ + { + "$id": "882", + "kind": "string", + "type": { + "$ref": "111" + }, + "value": "https://contoso.developer.azure-api.net" + } + ] + } + } + } + } + } + ] + }, + "nextLink": { + "$id": "883", + "kind": "string", + "type": { + "$ref": "126" + }, + "value": "https://..." + } + } + } + } + ] + } + ] + }, + { + "$id": "884", + "name": "get", + "resourceName": "Environment", + "doc": "Get an environment.", + "accessibility": "public", + "parameters": [ + { + "$id": "885", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "886", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "887", + "type": { + "$id": "888", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "889", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "890", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "891", + "name": "environmentName", + "nameInRequest": "environmentName", + "doc": "Environment identifier.", + "type": { + "$id": "892", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "893", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "894", + "kind": "constant", + "valueType": { + "$id": "895", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "896", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "74" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/environments/{environmentName}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environments.get", + "decorators": [], + "examples": [ + { + "$id": "897", + "kind": "http", + "name": "Environments_Get", + "description": "Environments_Get", + "filePath": "2024-02-01-preview/Environments_Get.json", + "parameters": [ + { + "$id": "898", + "parameter": { + "$ref": "885" + }, + "value": { + "$id": "899", + "kind": "string", + "type": { + "$ref": "886" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "900", + "parameter": { + "$ref": "889" + }, + "value": { + "$id": "901", + "kind": "string", + "type": { + "$ref": "890" + }, + "value": "default" + } + }, + { + "$id": "902", + "parameter": { + "$ref": "891" + }, + "value": { + "$id": "903", + "kind": "string", + "type": { + "$ref": "892" + }, + "value": "production" + } + } + ], + "responses": [ + { + "$id": "904", + "response": { + "$ref": "896" + }, + "statusCode": 200, + "bodyValue": { + "$id": "905", + "kind": "model", + "type": { + "$ref": "74" + }, + "value": { + "$id": "906", + "name": { + "$id": "907", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "public" + }, + "title": { + "$id": "908", + "kind": "string", + "type": { + "$ref": "80" + }, + "value": "Public" + }, + "description": { + "$id": "909", + "kind": "string", + "type": { + "$ref": "87" + }, + "value": "Public Cloud environment." + }, + "kind": { + "$id": "910", + "kind": "string", + "type": { + "$ref": "18" + }, + "value": "production" + }, + "server": { + "$id": "911", + "kind": "model", + "type": { + "$ref": "91" + }, + "value": { + "$id": "912", + "type": { + "$id": "913", + "kind": "string", + "type": { + "$ref": "93" + }, + "value": "Azure API Management" + }, + "managementPortalUris": { + "$id": "914", + "kind": "array", + "type": { + "$ref": "97" + }, + "value": [ + { + "$id": "915", + "kind": "string", + "type": { + "$ref": "98" + }, + "value": "https://portal.azure.com" + } + ] + } + } + }, + "onboarding": { + "$id": "916", + "kind": "model", + "type": { + "$ref": "104" + }, + "value": { + "$id": "917", + "instructions": { + "$id": "918", + "kind": "string", + "type": { + "$ref": "106" + }, + "value": "https://aka.ms/apim-devportal" + }, + "developerPortalUris": { + "$id": "919", + "kind": "array", + "type": { + "$ref": "110" + }, + "value": [ + { + "$id": "920", + "kind": "string", + "type": { + "$ref": "111" + }, + "value": "https://contoso.developer.azure-api.net" + } + ] + } + } + } + } + } + } + ] + } + ] + } + ], + "parameters": [], + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.Environments", + "apiVersions": [ + "2024-02-01-preview" + ], + "parent": { + "$ref": "393" + } + }, + { + "$id": "921", + "kind": "client", + "name": "ApiVersions", + "namespace": "azure.ApiCenter", + "operations": [ + { + "$id": "922", + "name": "listVersions", + "resourceName": "ApiVersion", + "doc": "List a collection of API versions.", + "accessibility": "public", + "parameters": [ + { + "$id": "923", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "924", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "925", + "type": { + "$id": "926", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "927", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "928", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "929", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "930", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "931", + "name": "top", + "nameInRequest": "top", + "doc": "The number of result items to return.", + "type": { + "$id": "932", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "933", + "name": "skip", + "nameInRequest": "skip", + "doc": "The number of result items to skip.", + "type": { + "$id": "934", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "935", + "name": "maxpagesize", + "nameInRequest": "maxpagesize", + "doc": "The maximum number of result items per page.", + "type": { + "$id": "936", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "937", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "938", + "kind": "constant", + "valueType": { + "$id": "939", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "940", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "383" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/versions", + "bufferResponse": true, + "paging": { + "$id": "941", + "itemPropertySegments": [ + "value" + ], + "nextLink": { + "$id": "942", + "responseSegments": [ + "nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiVersions.listVersions", + "decorators": [], + "examples": [ + { + "$id": "943", + "kind": "http", + "name": "ApiVersions_ListVersions", + "description": "ApiVersions_ListVersions", + "filePath": "2024-02-01-preview/ApiVersions_ListVersions.json", + "parameters": [ + { + "$id": "944", + "parameter": { + "$ref": "923" + }, + "value": { + "$id": "945", + "kind": "string", + "type": { + "$ref": "924" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "946", + "parameter": { + "$ref": "927" + }, + "value": { + "$id": "947", + "kind": "string", + "type": { + "$ref": "928" + }, + "value": "default" + } + }, + { + "$id": "948", + "parameter": { + "$ref": "929" + }, + "value": { + "$id": "949", + "kind": "string", + "type": { + "$ref": "930" + }, + "value": "echo-api" + } + } + ], + "responses": [ + { + "$id": "950", + "response": { + "$ref": "940" + }, + "statusCode": 200, + "bodyValue": { + "$id": "951", + "kind": "model", + "type": { + "$ref": "383" + }, + "value": { + "$id": "952", + "value": { + "$id": "953", + "kind": "array", + "type": { + "$ref": "385" + }, + "value": [ + { + "$id": "954", + "kind": "model", + "type": { + "$ref": "62" + }, + "value": { + "$id": "955", + "name": { + "$id": "956", + "kind": "string", + "type": { + "$ref": "64" + }, + "value": "2023-01-01" + }, + "title": { + "$id": "957", + "kind": "string", + "type": { + "$ref": "68" + }, + "value": "2023-01-01" + }, + "lifecycleStage": { + "$id": "958", + "kind": "string", + "type": { + "$ref": "2" + }, + "value": "design" + } + } + } + ] + }, + "nextLink": { + "$id": "959", + "kind": "string", + "type": { + "$ref": "389" + }, + "value": "https://..." + } + } + } + } + ] + } + ] + }, + { + "$id": "960", + "name": "getVersion", + "resourceName": "ApiVersion", + "doc": "Get an API version.", + "accessibility": "public", + "parameters": [ + { + "$id": "961", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "962", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "963", + "type": { + "$id": "964", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-02-01-preview" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "965", + "name": "workspaceName", + "nameInRequest": "workspaceName", + "doc": "Workspace identifier.", + "type": { + "$id": "966", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "967", + "name": "apiName", + "nameInRequest": "apiName", + "doc": "Api identifier.", + "type": { + "$id": "968", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "969", + "name": "versionName", + "nameInRequest": "versionName", + "doc": "Version identifier.", + "type": { + "$id": "970", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "971", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "972", + "kind": "constant", + "valueType": { + "$id": "973", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "974", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "62" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "https://{serviceName}.data.{region}.azure-apicenter.ms", + "path": "/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiVersions.getVersion", + "decorators": [], + "examples": [ + { + "$id": "975", + "kind": "http", + "name": "ApiVersions_GetVersion", + "description": "ApiVersions_GetVersion", + "filePath": "2024-02-01-preview/ApiVersions_GetVersion.json", + "parameters": [ + { + "$id": "976", + "parameter": { + "$ref": "961" + }, + "value": { + "$id": "977", + "kind": "string", + "type": { + "$ref": "962" + }, + "value": "2024-02-01-preview" + } + }, + { + "$id": "978", + "parameter": { + "$ref": "965" + }, + "value": { + "$id": "979", + "kind": "string", + "type": { + "$ref": "966" + }, + "value": "default" + } + }, + { + "$id": "980", + "parameter": { + "$ref": "967" + }, + "value": { + "$id": "981", + "kind": "string", + "type": { + "$ref": "968" + }, + "value": "echo-api" + } + }, + { + "$id": "982", + "parameter": { + "$ref": "969" + }, + "value": { + "$id": "983", + "kind": "string", + "type": { + "$ref": "970" + }, + "value": "2023-01-01" + } + } + ], + "responses": [ + { + "$id": "984", + "response": { + "$ref": "974" + }, + "statusCode": 200, + "bodyValue": { + "$id": "985", + "kind": "model", + "type": { + "$ref": "62" + }, + "value": { + "$id": "986", + "name": { + "$id": "987", + "kind": "string", + "type": { + "$ref": "64" + }, + "value": "2023-01-01" + }, + "title": { + "$id": "988", + "kind": "string", + "type": { + "$ref": "68" + }, + "value": "2023-01-01" + }, + "lifecycleStage": { + "$id": "989", + "kind": "string", + "type": { + "$ref": "2" + }, + "value": "design" + } + } + } + } + ] + } + ] + } + ], + "parameters": [], + "decorators": [], + "crossLanguageDefinitionId": "ApiCenter.DataApi.ApiVersions", + "apiVersions": [ + "2024-02-01-preview" + ], + "parent": { + "$ref": "393" + } + } + ] + } + ], + "auth": { + "$id": "990", + "oAuth2": { + "$id": "991", + "scopes": [ + "https://azure-apicenter.net/user_impersonation" + ] + } + } +} diff --git a/sdk/appconfiguration/Azure.Data.AppConfiguration/Configuration.json b/sdk/appconfiguration/Azure.Data.AppConfiguration/Configuration.json new file mode 100644 index 000000000000..ede625681568 --- /dev/null +++ b/sdk/appconfiguration/Azure.Data.AppConfiguration/Configuration.json @@ -0,0 +1,12 @@ +{ + "output-folder": ".", + "namespace": "Azure.Data.AppConfiguration", + "library-name": "Azure.Data.AppConfiguration", + "flavor": "azure", + "use-model-reader-writer": true, + "shared-source-folders": [ + "../../TempTypeSpecFiles/node_modules/@autorest/csharp/Generator.Shared", + "../../TempTypeSpecFiles/node_modules/@autorest/csharp/Azure.Core.Shared" + ], + "model-namespace": false +} diff --git a/sdk/appconfiguration/Azure.Data.AppConfiguration/src/autorest.md b/sdk/appconfiguration/Azure.Data.AppConfiguration/src/autorest.md deleted file mode 100644 index af1f2ccf84c9..000000000000 --- a/sdk/appconfiguration/Azure.Data.AppConfiguration/src/autorest.md +++ /dev/null @@ -1,55 +0,0 @@ -# Azure SDK Code Generation for Data Plane - -Run `dotnet build /t:GenerateCode` to generate code. - -### AutoRest Configuration -> see https://aka.ms/autorest -``` yaml -input-file: -- https://github.com/Azure/azure-rest-api-specs/blob/c1af3ab8e803da2f40fc90217a6d023bc13b677f/specification/appconfiguration/data-plane/Microsoft.AppConfiguration/stable/2023-11-01/appconfiguration.json -namespace: Azure.Data.AppConfiguration -title: ConfigurationClient -``` - -### Change Endpoint type to Uri -``` yaml -directive: - from: swagger-document - where: $.parameters.Endpoint - transform: $.format = "url" - ``` - -### Modify operation names -``` yaml -directive: -- rename-operation: - from: PutKeyValue - to: SetConfigurationSetting -- rename-operation: - from: DeleteKeyValue - to: DeleteConfigurationSetting -- rename-operation: - from: GetKeyValue - to: GetConfigurationSetting -- rename-operation: - from: GetKeyValues - to: GetConfigurationSettings -- rename-operation: - from: PutLock - to: CreateReadOnlyLock -- rename-operation: - from: DeleteLock - to: DeleteReadOnlyLock -- rename-operation: - from: UpdateSnapshot - to: UpdateSnapshotStatus -``` - -### Internalize protocol methods -``` yaml -directive: - from: swagger-document - where: $.paths.*.* - transform: > - $["x-accessibility"] = "internal" -``` diff --git a/sdk/appconfiguration/Azure.Data.AppConfiguration/tsp-location.yaml b/sdk/appconfiguration/Azure.Data.AppConfiguration/tsp-location.yaml new file mode 100644 index 000000000000..f740a4ff25d1 --- /dev/null +++ b/sdk/appconfiguration/Azure.Data.AppConfiguration/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/appconfiguration/AppConfiguration +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/appconfiguration/Azure.Data.AppConfiguration/tspCodeModel.json b/sdk/appconfiguration/Azure.Data.AppConfiguration/tspCodeModel.json new file mode 100644 index 000000000000..cd6103b64550 --- /dev/null +++ b/sdk/appconfiguration/Azure.Data.AppConfiguration/tspCodeModel.json @@ -0,0 +1,13365 @@ +{ + "$id": "1", + "name": "AzureAppConfiguration", + "apiVersions": [ + "2023-11-01", + "2024-09-01" + ], + "enums": [ + { + "$id": "2", + "kind": "enum", + "name": "GetKeysResponseContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.getKeys.ResponseContentType.anonymous", + "valueType": { + "$id": "3", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "4", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.keyset+json", + "value": "application/vnd.microsoft.appconfig.keyset+json", + "valueType": { + "$id": "5", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "decorators": [] + }, + { + "$id": "6", + "kind": "enumvalue", + "name": "application/problem+json", + "value": "application/problem+json", + "valueType": { + "$id": "7", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "2" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Output", + "decorators": [] + }, + { + "$id": "8", + "kind": "enum", + "name": "KeyValueFields", + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueFields", + "valueType": { + "$id": "9", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "10", + "kind": "enumvalue", + "name": "key", + "value": "key", + "valueType": { + "$id": "11", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Key field.", + "decorators": [] + }, + { + "$id": "12", + "kind": "enumvalue", + "name": "label", + "value": "label", + "valueType": { + "$id": "13", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Label field.", + "decorators": [] + }, + { + "$id": "14", + "kind": "enumvalue", + "name": "content_type", + "value": "content_type", + "valueType": { + "$id": "15", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Content type field.", + "decorators": [] + }, + { + "$id": "16", + "kind": "enumvalue", + "name": "value", + "value": "value", + "valueType": { + "$id": "17", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Value field.", + "decorators": [] + }, + { + "$id": "18", + "kind": "enumvalue", + "name": "last_modified", + "value": "last_modified", + "valueType": { + "$id": "19", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Last modified field.", + "decorators": [] + }, + { + "$id": "20", + "kind": "enumvalue", + "name": "tags", + "value": "tags", + "valueType": { + "$id": "21", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Tags field.", + "decorators": [] + }, + { + "$id": "22", + "kind": "enumvalue", + "name": "locked", + "value": "locked", + "valueType": { + "$id": "23", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Locked field.", + "decorators": [] + }, + { + "$id": "24", + "kind": "enumvalue", + "name": "etag", + "value": "etag", + "valueType": { + "$id": "25", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "8" + }, + "doc": "Etag field.", + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "doc": "Key-value fields.", + "isFixed": false, + "isFlags": false, + "usage": "Input", + "decorators": [] + }, + { + "$id": "26", + "kind": "enum", + "name": "GetKeyValuesResponseContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.getKeyValues.ResponseContentType.anonymous", + "valueType": { + "$id": "27", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "28", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.kvset+json", + "value": "application/vnd.microsoft.appconfig.kvset+json", + "valueType": { + "$id": "29", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "26" + }, + "decorators": [] + }, + { + "$id": "30", + "kind": "enumvalue", + "name": "application/problem+json", + "value": "application/problem+json", + "valueType": { + "$id": "31", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "26" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Output", + "decorators": [] + }, + { + "$id": "32", + "kind": "enum", + "name": "GetKeyValueResponseContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.getKeyValue.ResponseContentType.anonymous", + "valueType": { + "$id": "33", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "34", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.kv+json", + "value": "application/vnd.microsoft.appconfig.kv+json", + "valueType": { + "$id": "35", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "decorators": [] + }, + { + "$id": "36", + "kind": "enumvalue", + "name": "application/problem+json", + "value": "application/problem+json", + "valueType": { + "$id": "37", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "32" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Output", + "decorators": [] + }, + { + "$id": "38", + "kind": "enum", + "name": "PutKeyValueRequestContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.putKeyValue.RequestContentType.anonymous", + "valueType": { + "$id": "39", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "40", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.kv+json", + "value": "application/vnd.microsoft.appconfig.kv+json", + "valueType": { + "$id": "41", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "38" + }, + "decorators": [] + }, + { + "$id": "42", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.kvset+json", + "value": "application/vnd.microsoft.appconfig.kvset+json", + "valueType": { + "$id": "43", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "38" + }, + "decorators": [] + }, + { + "$id": "44", + "kind": "enumvalue", + "name": "application/json", + "value": "application/json", + "valueType": { + "$id": "45", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "38" + }, + "decorators": [] + }, + { + "$id": "46", + "kind": "enumvalue", + "name": "text/json", + "value": "text/json", + "valueType": { + "$id": "47", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "38" + }, + "decorators": [] + }, + { + "$id": "48", + "kind": "enumvalue", + "name": "application/*+json", + "value": "application/*+json", + "valueType": { + "$id": "49", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "38" + }, + "decorators": [] + }, + { + "$id": "50", + "kind": "enumvalue", + "name": "application/json-patch+json", + "value": "application/json-patch+json", + "valueType": { + "$id": "51", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "38" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Input", + "decorators": [] + }, + { + "$id": "52", + "kind": "enum", + "name": "SnapshotFields", + "crossLanguageDefinitionId": "AzureAppConfiguration.SnapshotFields", + "valueType": { + "$id": "53", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "54", + "kind": "enumvalue", + "name": "name", + "value": "name", + "valueType": { + "$id": "55", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Name field.", + "decorators": [] + }, + { + "$id": "56", + "kind": "enumvalue", + "name": "status", + "value": "status", + "valueType": { + "$id": "57", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Status field.", + "decorators": [] + }, + { + "$id": "58", + "kind": "enumvalue", + "name": "filters", + "value": "filters", + "valueType": { + "$id": "59", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Filters field.", + "decorators": [] + }, + { + "$id": "60", + "kind": "enumvalue", + "name": "composition_type", + "value": "composition_type", + "valueType": { + "$id": "61", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Composition type field.", + "decorators": [] + }, + { + "$id": "62", + "kind": "enumvalue", + "name": "created", + "value": "created", + "valueType": { + "$id": "63", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Created field.", + "decorators": [] + }, + { + "$id": "64", + "kind": "enumvalue", + "name": "expires", + "value": "expires", + "valueType": { + "$id": "65", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Expires field.", + "decorators": [] + }, + { + "$id": "66", + "kind": "enumvalue", + "name": "retention_period", + "value": "retention_period", + "valueType": { + "$id": "67", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Retention period field.", + "decorators": [] + }, + { + "$id": "68", + "kind": "enumvalue", + "name": "size", + "value": "size", + "valueType": { + "$id": "69", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Size field.", + "decorators": [] + }, + { + "$id": "70", + "kind": "enumvalue", + "name": "items_count", + "value": "items_count", + "valueType": { + "$id": "71", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Items count field.", + "decorators": [] + }, + { + "$id": "72", + "kind": "enumvalue", + "name": "tags", + "value": "tags", + "valueType": { + "$id": "73", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Tags field.", + "decorators": [] + }, + { + "$id": "74", + "kind": "enumvalue", + "name": "etag", + "value": "etag", + "valueType": { + "$id": "75", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "52" + }, + "doc": "Etag field.", + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "doc": "Snapshot fields.", + "isFixed": false, + "isFlags": false, + "usage": "Input", + "decorators": [] + }, + { + "$id": "76", + "kind": "enum", + "name": "SnapshotStatus", + "crossLanguageDefinitionId": "AzureAppConfiguration.SnapshotStatus", + "valueType": { + "$id": "77", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "78", + "kind": "enumvalue", + "name": "provisioning", + "value": "provisioning", + "valueType": { + "$id": "79", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "76" + }, + "doc": "Provisioning", + "decorators": [] + }, + { + "$id": "80", + "kind": "enumvalue", + "name": "ready", + "value": "ready", + "valueType": { + "$id": "81", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "76" + }, + "doc": "Ready", + "decorators": [] + }, + { + "$id": "82", + "kind": "enumvalue", + "name": "archived", + "value": "archived", + "valueType": { + "$id": "83", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "76" + }, + "doc": "Archived", + "decorators": [] + }, + { + "$id": "84", + "kind": "enumvalue", + "name": "failed", + "value": "failed", + "valueType": { + "$id": "85", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "76" + }, + "doc": "Failed", + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "doc": "Snapshot status.", + "isFixed": false, + "isFlags": false, + "usage": "Input,Output,JsonMergePatch,Json,LroInitial,LroFinalEnvelope", + "decorators": [] + }, + { + "$id": "86", + "kind": "enum", + "name": "CompositionType", + "crossLanguageDefinitionId": "AzureAppConfiguration.CompositionType", + "valueType": { + "$id": "87", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "88", + "kind": "enumvalue", + "name": "key", + "value": "key", + "valueType": { + "$id": "89", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "86" + }, + "doc": "The 'key' composition type.", + "decorators": [] + }, + { + "$id": "90", + "kind": "enumvalue", + "name": "key_label", + "value": "key_label", + "valueType": { + "$id": "91", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "86" + }, + "doc": "The 'key_label' composition type.", + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "doc": "Composition types.", + "isFixed": false, + "isFlags": false, + "usage": "Input,Output,Json,LroInitial,LroFinalEnvelope", + "decorators": [] + }, + { + "$id": "92", + "kind": "enum", + "name": "GetSnapshotsResponseContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.getSnapshots.ResponseContentType.anonymous", + "valueType": { + "$id": "93", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "94", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.snapshotset+json", + "value": "application/vnd.microsoft.appconfig.snapshotset+json", + "valueType": { + "$id": "95", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "92" + }, + "decorators": [] + }, + { + "$id": "96", + "kind": "enumvalue", + "name": "application/problem+json", + "value": "application/problem+json", + "valueType": { + "$id": "97", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "92" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Output", + "decorators": [] + }, + { + "$id": "98", + "kind": "enum", + "name": "GetSnapshotResponseContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.getSnapshot.ResponseContentType.anonymous", + "valueType": { + "$id": "99", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "100", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.snapshot+json", + "value": "application/vnd.microsoft.appconfig.snapshot+json", + "valueType": { + "$id": "101", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "98" + }, + "decorators": [] + }, + { + "$id": "102", + "kind": "enumvalue", + "name": "application/problem+json", + "value": "application/problem+json", + "valueType": { + "$id": "103", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "98" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Output", + "decorators": [] + }, + { + "$id": "104", + "kind": "enum", + "name": "OperationState", + "crossLanguageDefinitionId": "Azure.Core.Foundations.OperationState", + "valueType": { + "$id": "105", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "106", + "kind": "enumvalue", + "name": "NotStarted", + "value": "NotStarted", + "valueType": { + "$id": "107", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "104" + }, + "doc": "The operation has not started.", + "decorators": [] + }, + { + "$id": "108", + "kind": "enumvalue", + "name": "Running", + "value": "Running", + "valueType": { + "$id": "109", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "104" + }, + "doc": "The operation is in progress.", + "decorators": [] + }, + { + "$id": "110", + "kind": "enumvalue", + "name": "Succeeded", + "value": "Succeeded", + "valueType": { + "$id": "111", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "104" + }, + "doc": "The operation has completed successfully.", + "decorators": [] + }, + { + "$id": "112", + "kind": "enumvalue", + "name": "Failed", + "value": "Failed", + "valueType": { + "$id": "113", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "104" + }, + "doc": "The operation has failed.", + "decorators": [] + }, + { + "$id": "114", + "kind": "enumvalue", + "name": "Canceled", + "value": "Canceled", + "valueType": { + "$id": "115", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "104" + }, + "doc": "The operation has been canceled by the user.", + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "doc": "Enum describing allowed operation states.", + "isFixed": false, + "isFlags": false, + "usage": "Output,Json,LroPolling", + "decorators": [] + }, + { + "$id": "116", + "kind": "enum", + "name": "CreateSnapshotRequestContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.createSnapshot.RequestContentType.anonymous", + "valueType": { + "$id": "117", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "118", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.snapshot+json", + "value": "application/vnd.microsoft.appconfig.snapshot+json", + "valueType": { + "$id": "119", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "116" + }, + "decorators": [] + }, + { + "$id": "120", + "kind": "enumvalue", + "name": "application/json", + "value": "application/json", + "valueType": { + "$id": "121", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "116" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Input", + "decorators": [] + }, + { + "$id": "122", + "kind": "enum", + "name": "UpdateSnapshotRequestContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.updateSnapshot.RequestContentType.anonymous", + "valueType": { + "$id": "123", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "124", + "kind": "enumvalue", + "name": "application/merge-patch+json", + "value": "application/merge-patch+json", + "valueType": { + "$id": "125", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "122" + }, + "decorators": [] + }, + { + "$id": "126", + "kind": "enumvalue", + "name": "application/json", + "value": "application/json", + "valueType": { + "$id": "127", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "122" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Input", + "decorators": [] + }, + { + "$id": "128", + "kind": "enum", + "name": "LabelFields", + "crossLanguageDefinitionId": "AzureAppConfiguration.LabelFields", + "valueType": { + "$id": "129", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "130", + "kind": "enumvalue", + "name": "name", + "value": "name", + "valueType": { + "$id": "131", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "128" + }, + "doc": "Name field.", + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "doc": "Label fields.", + "isFixed": false, + "isFlags": false, + "usage": "Input", + "decorators": [] + }, + { + "$id": "132", + "kind": "enum", + "name": "GetLabelsResponseContentType", + "crossLanguageDefinitionId": "AzureAppConfiguration.getLabels.ResponseContentType.anonymous", + "valueType": { + "$id": "133", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "134", + "kind": "enumvalue", + "name": "application/vnd.microsoft.appconfig.labelset+json", + "value": "application/vnd.microsoft.appconfig.labelset+json", + "valueType": { + "$id": "135", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "132" + }, + "decorators": [] + }, + { + "$id": "136", + "kind": "enumvalue", + "name": "application/problem+json", + "value": "application/problem+json", + "valueType": { + "$id": "137", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "132" + }, + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "isFixed": true, + "isFlags": false, + "usage": "Output", + "decorators": [] + }, + { + "$id": "138", + "kind": "enum", + "name": "Versions", + "crossLanguageDefinitionId": "AzureAppConfiguration.Versions", + "valueType": { + "$id": "139", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "values": [ + { + "$id": "140", + "kind": "enumvalue", + "name": "v2023_11_01", + "value": "2023-11-01", + "valueType": { + "$id": "141", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "138" + }, + "doc": "The 2023-11-01 API version", + "decorators": [] + }, + { + "$id": "142", + "kind": "enumvalue", + "name": "v2024_09_01", + "value": "2024-09-01", + "valueType": { + "$id": "143", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "enumType": { + "$ref": "138" + }, + "doc": "The 2024-09-01 API version", + "decorators": [] + } + ], + "namespace": "Azure.Data.AppConfiguration", + "doc": "Service API versions", + "isFixed": true, + "isFlags": false, + "usage": "ApiVersionEnum", + "decorators": [] + } + ], + "models": [ + { + "$id": "144", + "kind": "model", + "name": "KeyListResult", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyListResult", + "usage": "Output,Json", + "doc": "The result of a list request.", + "decorators": [], + "properties": [ + { + "$id": "145", + "kind": "property", + "name": "items", + "serializedName": "items", + "doc": "The collection value.", + "type": { + "$id": "146", + "kind": "array", + "name": "ArrayKey", + "valueType": { + "$id": "147", + "kind": "model", + "name": "Key", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.Key", + "usage": "Output,Json", + "doc": "Keys serve as identifiers for key-values and are used to store and retrieve corresponding values.", + "decorators": [], + "properties": [ + { + "$id": "148", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "The name of the key.", + "type": { + "$id": "149", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Key.name", + "serializationOptions": { + "$id": "150", + "json": { + "$id": "151", + "name": "name" + } + } + } + ] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyListResult.items", + "serializationOptions": { + "$id": "152", + "json": { + "$id": "153", + "name": "items" + } + } + }, + { + "$id": "154", + "kind": "property", + "name": "@nextLink", + "serializedName": "@nextLink", + "doc": "The URI that can be used to request the next set of paged results.", + "type": { + "$id": "155", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyListResult.@nextLink", + "serializationOptions": { + "$id": "156", + "json": { + "$id": "157", + "name": "@nextLink" + } + } + } + ] + }, + { + "$ref": "147" + }, + { + "$id": "158", + "kind": "model", + "name": "Error", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.Error", + "usage": "Error,Json,Exception", + "doc": "Azure App Configuration error object.", + "decorators": [], + "properties": [ + { + "$id": "159", + "kind": "property", + "name": "type", + "serializedName": "type", + "doc": "The type of the error.", + "type": { + "$id": "160", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Error.type", + "serializationOptions": { + "$id": "161", + "json": { + "$id": "162", + "name": "type" + } + } + }, + { + "$id": "163", + "kind": "property", + "name": "title", + "serializedName": "title", + "doc": "A brief summary of the error.", + "type": { + "$id": "164", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Error.title", + "serializationOptions": { + "$id": "165", + "json": { + "$id": "166", + "name": "title" + } + } + }, + { + "$id": "167", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "The name of the parameter that resulted in the error.", + "type": { + "$id": "168", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Error.name", + "serializationOptions": { + "$id": "169", + "json": { + "$id": "170", + "name": "name" + } + } + }, + { + "$id": "171", + "kind": "property", + "name": "detail", + "serializedName": "detail", + "doc": "A detailed description of the error.", + "type": { + "$id": "172", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Error.detail", + "serializationOptions": { + "$id": "173", + "json": { + "$id": "174", + "name": "detail" + } + } + }, + { + "$id": "175", + "kind": "property", + "name": "status", + "serializedName": "status", + "doc": "The HTTP status code that the error maps to.", + "type": { + "$id": "176", + "kind": "int32", + "name": "int32", + "crossLanguageDefinitionId": "TypeSpec.int32", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Error.status", + "serializationOptions": { + "$id": "177", + "json": { + "$id": "178", + "name": "status" + } + } + } + ] + }, + { + "$id": "179", + "kind": "model", + "name": "KeyValueListResult", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueListResult", + "usage": "Output,Json", + "doc": "The result of a list request.", + "decorators": [], + "properties": [ + { + "$id": "180", + "kind": "property", + "name": "items", + "serializedName": "items", + "doc": "The collection value.", + "type": { + "$id": "181", + "kind": "array", + "name": "ArrayKeyValue", + "valueType": { + "$id": "182", + "kind": "model", + "name": "KeyValue", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue", + "usage": "Input,Output,Json", + "doc": "A key-value pair representing application settings.", + "decorators": [], + "properties": [ + { + "$id": "183", + "kind": "property", + "name": "key", + "serializedName": "key", + "doc": "The key of the key-value.", + "type": { + "$id": "184", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.key", + "serializationOptions": { + "$id": "185", + "json": { + "$id": "186", + "name": "key" + } + } + }, + { + "$id": "187", + "kind": "property", + "name": "label", + "serializedName": "label", + "doc": "The label the key-value belongs to.", + "type": { + "$id": "188", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.label", + "serializationOptions": { + "$id": "189", + "json": { + "$id": "190", + "name": "label" + } + } + }, + { + "$id": "191", + "kind": "property", + "name": "contentType", + "serializedName": "content_type", + "doc": "The content type of the value stored within the key-value.", + "type": { + "$id": "192", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.contentType", + "serializationOptions": { + "$id": "193", + "json": { + "$id": "194", + "name": "content_type" + } + } + }, + { + "$id": "195", + "kind": "property", + "name": "value", + "serializedName": "value", + "doc": "The value of the key-value.", + "type": { + "$id": "196", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.value", + "serializationOptions": { + "$id": "197", + "json": { + "$id": "198", + "name": "value" + } + } + }, + { + "$id": "199", + "kind": "property", + "name": "lastModified", + "serializedName": "last_modified", + "doc": "A date representing the last time the key-value was modified.", + "type": { + "$id": "200", + "kind": "offsetDateTime", + "name": "offsetDateTime", + "encode": "rfc3339", + "wireType": { + "$id": "201", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.offsetDateTime", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.lastModified", + "serializationOptions": { + "$id": "202", + "json": { + "$id": "203", + "name": "last_modified" + } + } + }, + { + "$id": "204", + "kind": "property", + "name": "tags", + "serializedName": "tags", + "doc": "The tags of the key-value", + "type": { + "$id": "205", + "kind": "dict", + "keyType": { + "$id": "206", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "valueType": { + "$id": "207", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.tags", + "serializationOptions": { + "$id": "208", + "json": { + "$id": "209", + "name": "tags" + } + } + }, + { + "$id": "210", + "kind": "property", + "name": "locked", + "serializedName": "locked", + "doc": "Indicates whether the key-value is locked.", + "type": { + "$id": "211", + "kind": "boolean", + "name": "boolean", + "crossLanguageDefinitionId": "TypeSpec.boolean", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.locked", + "serializationOptions": { + "$id": "212", + "json": { + "$id": "213", + "name": "locked" + } + } + }, + { + "$id": "214", + "kind": "property", + "name": "etag", + "serializedName": "etag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "215", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValue.etag", + "serializationOptions": { + "$id": "216", + "json": { + "$id": "217", + "name": "etag" + } + } + } + ] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueListResult.items", + "serializationOptions": { + "$id": "218", + "json": { + "$id": "219", + "name": "items" + } + } + }, + { + "$id": "220", + "kind": "property", + "name": "etag", + "serializedName": "etag", + "doc": "An identifier representing the returned state of the resource.", + "type": { + "$id": "221", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueListResult.etag", + "serializationOptions": { + "$id": "222", + "json": { + "$id": "223", + "name": "etag" + } + } + }, + { + "$id": "224", + "kind": "property", + "name": "@nextLink", + "serializedName": "@nextLink", + "doc": "The URI that can be used to request the next set of paged results.", + "type": { + "$id": "225", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueListResult.@nextLink", + "serializationOptions": { + "$id": "226", + "json": { + "$id": "227", + "name": "@nextLink" + } + } + } + ] + }, + { + "$ref": "182" + }, + { + "$id": "228", + "kind": "model", + "name": "SnapshotListResult", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.SnapshotListResult", + "usage": "Output,Json", + "doc": "The result of a snapshot list request.", + "decorators": [], + "properties": [ + { + "$id": "229", + "kind": "property", + "name": "items", + "serializedName": "items", + "doc": "The collection value.", + "type": { + "$id": "230", + "kind": "array", + "name": "ArraySnapshot", + "valueType": { + "$id": "231", + "kind": "model", + "name": "Snapshot", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot", + "usage": "Input,Output,Json,LroInitial,LroFinalEnvelope", + "doc": "A snapshot is a named, immutable subset of an App Configuration store's key-values.", + "decorators": [], + "properties": [ + { + "$id": "232", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "The name of the snapshot.", + "type": { + "$id": "233", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.name", + "serializationOptions": { + "$id": "234", + "json": { + "$id": "235", + "name": "name" + } + } + }, + { + "$id": "236", + "kind": "property", + "name": "status", + "serializedName": "status", + "doc": "The current status of the snapshot.", + "type": { + "$ref": "76" + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.status", + "serializationOptions": { + "$id": "237", + "json": { + "$id": "238", + "name": "status" + } + } + }, + { + "$id": "239", + "kind": "property", + "name": "filters", + "serializedName": "filters", + "doc": "A list of filters used to filter the key-values included in the snapshot.", + "type": { + "$id": "240", + "kind": "array", + "name": "ArrayKeyValueFilter", + "valueType": { + "$id": "241", + "kind": "model", + "name": "KeyValueFilter", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueFilter", + "usage": "Input,Output,Json,LroInitial,LroFinalEnvelope", + "doc": "Enables filtering of key-values. Syntax reference:\nhttps://aka.ms/azconfig/docs/restapisnapshots", + "decorators": [], + "properties": [ + { + "$id": "242", + "kind": "property", + "name": "key", + "serializedName": "key", + "doc": "Filters key-values by their key field.", + "type": { + "$id": "243", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueFilter.key", + "serializationOptions": { + "$id": "244", + "json": { + "$id": "245", + "name": "key" + } + } + }, + { + "$id": "246", + "kind": "property", + "name": "label", + "serializedName": "label", + "doc": "Filters key-values by their label field.", + "type": { + "$id": "247", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueFilter.label", + "serializationOptions": { + "$id": "248", + "json": { + "$id": "249", + "name": "label" + } + } + }, + { + "$id": "250", + "kind": "property", + "name": "tags", + "serializedName": "tags", + "doc": "Filters key-values by their tags field.", + "type": { + "$id": "251", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "252", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.KeyValueFilter.tags", + "serializationOptions": { + "$id": "253", + "json": { + "$id": "254", + "name": "tags" + } + } + } + ] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.filters", + "serializationOptions": { + "$id": "255", + "json": { + "$id": "256", + "name": "filters" + } + } + }, + { + "$id": "257", + "kind": "property", + "name": "compositionType", + "serializedName": "composition_type", + "doc": "The composition type describes how the key-values within the snapshot are\ncomposed. The 'key' composition type ensures there are no two key-values\ncontaining the same key. The 'key_label' composition type ensures there are no\ntwo key-values containing the same key and label.", + "type": { + "$ref": "86" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.compositionType", + "serializationOptions": { + "$id": "258", + "json": { + "$id": "259", + "name": "composition_type" + } + } + }, + { + "$id": "260", + "kind": "property", + "name": "created", + "serializedName": "created", + "doc": "The time that the snapshot was created.", + "type": { + "$id": "261", + "kind": "offsetDateTime", + "name": "offsetDateTime", + "encode": "rfc3339", + "wireType": { + "$id": "262", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.offsetDateTime", + "decorators": [] + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.created", + "serializationOptions": { + "$id": "263", + "json": { + "$id": "264", + "name": "created" + } + } + }, + { + "$id": "265", + "kind": "property", + "name": "expires", + "serializedName": "expires", + "doc": "The time that the snapshot will expire.", + "type": { + "$id": "266", + "kind": "offsetDateTime", + "name": "offsetDateTime", + "encode": "rfc3339", + "wireType": { + "$id": "267", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.offsetDateTime", + "decorators": [] + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.expires", + "serializationOptions": { + "$id": "268", + "json": { + "$id": "269", + "name": "expires" + } + } + }, + { + "$id": "270", + "kind": "property", + "name": "retentionPeriod", + "serializedName": "retention_period", + "doc": "The amount of time, in seconds, that a snapshot will remain in the archived\nstate before expiring. This property is only writable during the creation of a\nsnapshot. If not specified, the default lifetime of key-value revisions will be\nused.", + "type": { + "$id": "271", + "kind": "int64", + "name": "int64", + "crossLanguageDefinitionId": "TypeSpec.int64", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.retentionPeriod", + "serializationOptions": { + "$id": "272", + "json": { + "$id": "273", + "name": "retention_period" + } + } + }, + { + "$id": "274", + "kind": "property", + "name": "size", + "serializedName": "size", + "doc": "The size in bytes of the snapshot.", + "type": { + "$id": "275", + "kind": "int64", + "name": "int64", + "crossLanguageDefinitionId": "TypeSpec.int64", + "decorators": [] + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.size", + "serializationOptions": { + "$id": "276", + "json": { + "$id": "277", + "name": "size" + } + } + }, + { + "$id": "278", + "kind": "property", + "name": "itemsCount", + "serializedName": "items_count", + "doc": "The amount of key-values in the snapshot.", + "type": { + "$id": "279", + "kind": "int64", + "name": "int64", + "crossLanguageDefinitionId": "TypeSpec.int64", + "decorators": [] + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.itemsCount", + "serializationOptions": { + "$id": "280", + "json": { + "$id": "281", + "name": "items_count" + } + } + }, + { + "$id": "282", + "kind": "property", + "name": "tags", + "serializedName": "tags", + "doc": "The tags of the snapshot.", + "type": { + "$id": "283", + "kind": "dict", + "keyType": { + "$id": "284", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "valueType": { + "$id": "285", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.tags", + "serializationOptions": { + "$id": "286", + "json": { + "$id": "287", + "name": "tags" + } + } + }, + { + "$id": "288", + "kind": "property", + "name": "etag", + "serializedName": "etag", + "doc": "A value representing the current state of the snapshot.", + "type": { + "$id": "289", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": true, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Snapshot.etag", + "serializationOptions": { + "$id": "290", + "json": { + "$id": "291", + "name": "etag" + } + } + } + ] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.SnapshotListResult.items", + "serializationOptions": { + "$id": "292", + "json": { + "$id": "293", + "name": "items" + } + } + }, + { + "$id": "294", + "kind": "property", + "name": "@nextLink", + "serializedName": "@nextLink", + "doc": "The URI that can be used to request the next set of paged results.", + "type": { + "$id": "295", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.SnapshotListResult.@nextLink", + "serializationOptions": { + "$id": "296", + "json": { + "$id": "297", + "name": "@nextLink" + } + } + } + ] + }, + { + "$ref": "231" + }, + { + "$ref": "241" + }, + { + "$id": "298", + "kind": "model", + "name": "OperationDetails", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.OperationDetails", + "usage": "Output,Json,LroPolling", + "doc": "Details of a long running operation.", + "decorators": [], + "properties": [ + { + "$id": "299", + "kind": "property", + "name": "id", + "serializedName": "id", + "doc": "The unique id of the operation.", + "type": { + "$id": "300", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.OperationDetails.id", + "serializationOptions": { + "$id": "301", + "json": { + "$id": "302", + "name": "id" + } + } + }, + { + "$id": "303", + "kind": "property", + "name": "status", + "serializedName": "status", + "doc": "The current status of the operation", + "type": { + "$ref": "104" + }, + "optional": false, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.OperationDetails.status", + "serializationOptions": { + "$id": "304", + "json": { + "$id": "305", + "name": "status" + } + } + }, + { + "$id": "306", + "kind": "property", + "name": "error", + "serializedName": "error", + "doc": "An error, available when the status is `Failed`, describing why the operation\nfailed.", + "type": { + "$ref": "158" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.OperationDetails.error", + "serializationOptions": { + "$id": "307", + "json": { + "$id": "308", + "name": "error" + } + } + } + ] + }, + { + "$id": "309", + "kind": "model", + "name": "SnapshotUpdateParameters", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.SnapshotUpdateParameters", + "usage": "Input,JsonMergePatch,Json", + "doc": "Parameters used to update a snapshot.", + "decorators": [], + "properties": [ + { + "$id": "310", + "kind": "property", + "name": "status", + "serializedName": "status", + "doc": "The desired status of the snapshot.", + "type": { + "$ref": "76" + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.SnapshotUpdateParameters.status", + "serializationOptions": { + "$id": "311", + "json": { + "$id": "312", + "name": "status" + } + } + } + ] + }, + { + "$id": "313", + "kind": "model", + "name": "LabelListResult", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.LabelListResult", + "usage": "Output,Json", + "doc": "The result of a list request.", + "decorators": [], + "properties": [ + { + "$id": "314", + "kind": "property", + "name": "items", + "serializedName": "items", + "doc": "The collection value.", + "type": { + "$id": "315", + "kind": "array", + "name": "ArrayLabel", + "valueType": { + "$id": "316", + "kind": "model", + "name": "Label", + "namespace": "Azure.Data.AppConfiguration", + "crossLanguageDefinitionId": "AzureAppConfiguration.Label", + "usage": "Output,Json", + "doc": "Labels are used to group key-values.", + "decorators": [], + "properties": [ + { + "$id": "317", + "kind": "property", + "name": "name", + "serializedName": "name", + "doc": "The name of the label.", + "type": { + "$id": "318", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.Label.name", + "serializationOptions": { + "$id": "319", + "json": { + "$id": "320", + "name": "name" + } + } + } + ] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.LabelListResult.items", + "serializationOptions": { + "$id": "321", + "json": { + "$id": "322", + "name": "items" + } + } + }, + { + "$id": "323", + "kind": "property", + "name": "@nextLink", + "serializedName": "@nextLink", + "doc": "The URI that can be used to request the next set of paged results.", + "type": { + "$id": "324", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "optional": true, + "readOnly": false, + "discriminator": false, + "flatten": false, + "decorators": [], + "crossLanguageDefinitionId": "AzureAppConfiguration.LabelListResult.@nextLink", + "serializationOptions": { + "$id": "325", + "json": { + "$id": "326", + "name": "@nextLink" + } + } + } + ] + }, + { + "$ref": "316" + } + ], + "clients": [ + { + "$id": "327", + "kind": "client", + "name": "AzureAppConfigurationClient", + "namespace": "Azure.Data.AppConfiguration", + "doc": "Azure App Configuration REST API", + "operations": [ + { + "$id": "328", + "name": "getKeys", + "resourceName": "Key", + "summary": "Gets a list of keys.", + "doc": "Gets a list of keys.", + "accessibility": "public", + "parameters": [ + { + "$id": "329", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "330", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "331", + "type": { + "$id": "332", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "333", + "name": "name", + "nameInRequest": "name", + "doc": "A filter for the name of the returned keys.", + "type": { + "$id": "334", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "335", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "336", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "337", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "338", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "339", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "340", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "341", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "342", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "343", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "144" + }, + "headers": [ + { + "$id": "344", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "345", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "346", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "2" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.keyset+json", + "application/problem+json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/keys", + "bufferResponse": true, + "paging": { + "$id": "347", + "itemPropertySegments": [ + "items" + ], + "nextLink": { + "$id": "348", + "responseSegments": [ + "@nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getKeys", + "decorators": [], + "examples": [ + { + "$id": "349", + "kind": "http", + "name": "Gets a list of keys.", + "description": "Gets a list of keys.", + "filePath": "2024-09-01/GetKeys.json", + "parameters": [ + { + "$id": "350", + "parameter": { + "$ref": "329" + }, + "value": { + "$id": "351", + "kind": "string", + "type": { + "$ref": "330" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "352", + "response": { + "$ref": "343" + }, + "statusCode": 200, + "bodyValue": { + "$id": "353", + "kind": "model", + "type": { + "$ref": "144" + }, + "value": { + "$id": "354", + "items": { + "$id": "355", + "kind": "array", + "type": { + "$ref": "146" + }, + "value": [ + { + "$id": "356", + "kind": "model", + "type": { + "$ref": "147" + }, + "value": { + "$id": "357", + "name": { + "$id": "358", + "kind": "string", + "type": { + "$ref": "149" + }, + "value": "MaxRequests" + } + } + }, + { + "$id": "359", + "kind": "model", + "type": { + "$ref": "147" + }, + "value": { + "$id": "360", + "name": { + "$id": "361", + "kind": "string", + "type": { + "$ref": "149" + }, + "value": "RequestTimeout" + } + } + } + ] + } + } + } + } + ] + } + ] + }, + { + "$id": "362", + "name": "checkKeys", + "resourceName": "AzureAppConfiguration", + "summary": "Requests the headers and status of the given resource.", + "doc": "Requests the headers and status of the given resource.", + "accessibility": "public", + "parameters": [ + { + "$id": "363", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "364", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "365", + "type": { + "$id": "366", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "367", + "name": "name", + "nameInRequest": "name", + "doc": "A filter for the name of the returned keys.", + "type": { + "$id": "368", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "369", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "370", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "371", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "372", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "373", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "374", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "375", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "376", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "377", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "378", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "379", + "kind": "constant", + "valueType": { + "$id": "380", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "381", + "statusCodes": [ + 200 + ], + "headers": [ + { + "$id": "382", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "383", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "HEAD", + "uri": "{endpoint}", + "path": "/keys", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.checkKeys", + "decorators": [], + "examples": [ + { + "$id": "384", + "kind": "http", + "name": "Check keys", + "description": "Check keys", + "filePath": "2024-09-01/CheckKeys.json", + "parameters": [ + { + "$id": "385", + "parameter": { + "$ref": "363" + }, + "value": { + "$id": "386", + "kind": "string", + "type": { + "$ref": "364" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "387", + "response": { + "$ref": "381" + }, + "statusCode": 200 + } + ] + } + ] + }, + { + "$id": "388", + "name": "getKeyValues", + "resourceName": "KeyValue", + "summary": "Gets a list of key-values.", + "doc": "Gets a list of key-values.", + "accessibility": "public", + "parameters": [ + { + "$id": "389", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "390", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "391", + "type": { + "$id": "392", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "393", + "name": "key", + "nameInRequest": "key", + "doc": "A filter used to match keys. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "394", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "395", + "name": "label", + "nameInRequest": "label", + "doc": "A filter used to match labels. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "396", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "397", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "398", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "399", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "400", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "401", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "402", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "403", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "404", + "kind": "array", + "name": "ArrayKeyValueFields", + "valueType": { + "$ref": "8" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "405", + "name": "snapshot", + "nameInRequest": "snapshot", + "doc": "A filter used get key-values for a snapshot. The value should be the name of\nthe snapshot. Not valid when used with 'key' and 'label' filters.", + "type": { + "$id": "406", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "407", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "408", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "409", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "410", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "411", + "name": "tags", + "nameInRequest": "tags", + "doc": "A filter used to query by tags. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "412", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "413", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": true, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "414", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "415", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "416", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "179" + }, + "headers": [ + { + "$id": "417", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "418", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "419", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "420", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "421", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "26" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.kvset+json", + "application/problem+json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/kv", + "bufferResponse": true, + "paging": { + "$id": "422", + "itemPropertySegments": [ + "items" + ], + "nextLink": { + "$id": "423", + "responseSegments": [ + "@nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getKeyValues", + "decorators": [], + "examples": [ + { + "$id": "424", + "kind": "http", + "name": "Gets a list of key-values.", + "description": "Gets a list of key-values.", + "filePath": "2024-09-01/GetKeyValues.json", + "parameters": [ + { + "$id": "425", + "parameter": { + "$ref": "389" + }, + "value": { + "$id": "426", + "kind": "string", + "type": { + "$ref": "390" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "427", + "response": { + "$ref": "416" + }, + "statusCode": 200, + "bodyValue": { + "$id": "428", + "kind": "model", + "type": { + "$ref": "179" + }, + "value": { + "$id": "429", + "items": { + "$id": "430", + "kind": "array", + "type": { + "$ref": "181" + }, + "value": [ + { + "$id": "431", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "432", + "etag": { + "$id": "433", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "CTgHR5UrDKNj2nsoGWDOipST9Pv" + }, + "key": { + "$id": "434", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Background" + }, + "label": { + "$id": "435", + "kind": "string", + "type": { + "$ref": "188" + }, + "value": "Asset1" + }, + "value": { + "$id": "436", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "blue" + }, + "tags": { + "$id": "437", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "438" + } + }, + "locked": { + "$id": "439", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "440", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-03-04T17:12:23+00:00" + } + } + }, + { + "$id": "441", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "442", + "etag": { + "$id": "443", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "UTSN1zePHbBQ0npbRB6elGRRuH7" + }, + "key": { + "$id": "444", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "MaxLogFiles" + }, + "label": { + "$id": "445", + "kind": "string", + "type": { + "$ref": "188" + }, + "value": "Asset1" + }, + "value": { + "$id": "446", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "50" + }, + "tags": { + "$id": "447", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "448" + } + }, + "locked": { + "$id": "449", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "450", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-03-04T17:12:23+00:00" + } + } + }, + { + "$id": "451", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "452", + "etag": { + "$id": "453", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "7XpB48ET4VAlB9068ft6fKMyA3m" + }, + "key": { + "$id": "454", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "455", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World" + }, + "tags": { + "$id": "456", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "457" + } + }, + "locked": { + "$id": "458", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "459", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-06-20T16:52:23+00:00" + } + } + }, + { + "$id": "460", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "461", + "etag": { + "$id": "462", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "fAFm4jkGNB1hsIr4o0S5hnhCCvY" + }, + "key": { + "$id": "463", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "WebDemo:Settings:BackgroundColor" + }, + "value": { + "$id": "464", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "blue" + }, + "tags": { + "$id": "465", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "466" + } + }, + "locked": { + "$id": "467", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "468", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-06-20T15:48:01+00:00" + } + } + } + ] + } + } + } + } + ] + }, + { + "$id": "469", + "kind": "http", + "name": "Gets a list of key-values using the If-Match header.", + "description": "Gets a list of key-values using the If-Match header.", + "filePath": "2024-09-01/GetKeyValues_IfMatch.json", + "parameters": [ + { + "$id": "470", + "parameter": { + "$ref": "389" + }, + "value": { + "$id": "471", + "kind": "string", + "type": { + "$ref": "390" + }, + "value": "2024-09-01" + } + }, + { + "$id": "472", + "parameter": { + "$ref": "407" + }, + "value": { + "$id": "473", + "kind": "string", + "type": { + "$ref": "408" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "474", + "response": { + "$ref": "416" + }, + "statusCode": 200, + "bodyValue": { + "$id": "475", + "kind": "model", + "type": { + "$ref": "179" + }, + "value": { + "$id": "476", + "items": { + "$id": "477", + "kind": "array", + "type": { + "$ref": "181" + }, + "value": [ + { + "$id": "478", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "479", + "etag": { + "$id": "480", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "CTgHR5UrDKNj2nsoGWDOipST9Pv" + }, + "key": { + "$id": "481", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Background" + }, + "label": { + "$id": "482", + "kind": "string", + "type": { + "$ref": "188" + }, + "value": "Asset1" + }, + "value": { + "$id": "483", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "blue" + }, + "tags": { + "$id": "484", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "485" + } + }, + "locked": { + "$id": "486", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "487", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-03-04T17:12:23+00:00" + } + } + }, + { + "$id": "488", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "489", + "etag": { + "$id": "490", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "UTSN1zePHbBQ0npbRB6elGRRuH7" + }, + "key": { + "$id": "491", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "MaxLogFiles" + }, + "label": { + "$id": "492", + "kind": "string", + "type": { + "$ref": "188" + }, + "value": "Asset1" + }, + "value": { + "$id": "493", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "50" + }, + "tags": { + "$id": "494", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "495" + } + }, + "locked": { + "$id": "496", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "497", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-03-04T17:12:23+00:00" + } + } + }, + { + "$id": "498", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "499", + "etag": { + "$id": "500", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "7XpB48ET4VAlB9068ft6fKMyA3m" + }, + "key": { + "$id": "501", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "502", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World" + }, + "tags": { + "$id": "503", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "504" + } + }, + "locked": { + "$id": "505", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "506", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-06-20T16:52:23+00:00" + } + } + }, + { + "$id": "507", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "508", + "etag": { + "$id": "509", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "fAFm4jkGNB1hsIr4o0S5hnhCCvY" + }, + "key": { + "$id": "510", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "WebDemo:Settings:BackgroundColor" + }, + "value": { + "$id": "511", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "blue" + }, + "tags": { + "$id": "512", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "513" + } + }, + "locked": { + "$id": "514", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "515", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-06-20T15:48:01+00:00" + } + } + } + ] + } + } + } + } + ] + }, + { + "$id": "516", + "kind": "http", + "name": "Gets a list of key-values using the If-None-Match header.", + "description": "Gets a list of key-values using the If-None-Match header.", + "filePath": "2024-09-01/GetKeyValues_IfNoneMatch.json", + "parameters": [ + { + "$id": "517", + "parameter": { + "$ref": "389" + }, + "value": { + "$id": "518", + "kind": "string", + "type": { + "$ref": "390" + }, + "value": "2024-09-01" + } + }, + { + "$id": "519", + "parameter": { + "$ref": "409" + }, + "value": { + "$id": "520", + "kind": "string", + "type": { + "$ref": "410" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + } + } + ], + "responses": [ + { + "$id": "521", + "response": { + "$ref": "416" + }, + "statusCode": 200, + "bodyValue": { + "$id": "522", + "kind": "model", + "type": { + "$ref": "179" + }, + "value": { + "$id": "523", + "items": { + "$id": "524", + "kind": "array", + "type": { + "$ref": "181" + }, + "value": [ + { + "$id": "525", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "526", + "etag": { + "$id": "527", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "CTgHR5UrDKNj2nsoGWDOipST9Pv" + }, + "key": { + "$id": "528", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Background" + }, + "label": { + "$id": "529", + "kind": "string", + "type": { + "$ref": "188" + }, + "value": "Asset1" + }, + "value": { + "$id": "530", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "blue" + }, + "tags": { + "$id": "531", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "532" + } + }, + "locked": { + "$id": "533", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "534", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-03-04T17:12:23+00:00" + } + } + }, + { + "$id": "535", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "536", + "etag": { + "$id": "537", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "UTSN1zePHbBQ0npbRB6elGRRuH7" + }, + "key": { + "$id": "538", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "MaxLogFiles" + }, + "label": { + "$id": "539", + "kind": "string", + "type": { + "$ref": "188" + }, + "value": "Asset1" + }, + "value": { + "$id": "540", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "50" + }, + "tags": { + "$id": "541", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "542" + } + }, + "locked": { + "$id": "543", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "544", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-03-04T17:12:23+00:00" + } + } + }, + { + "$id": "545", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "546", + "etag": { + "$id": "547", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "7XpB48ET4VAlB9068ft6fKMyA3m" + }, + "key": { + "$id": "548", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "549", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World" + }, + "tags": { + "$id": "550", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "551" + } + }, + "locked": { + "$id": "552", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "553", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-06-20T16:52:23+00:00" + } + } + }, + { + "$id": "554", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "555", + "etag": { + "$id": "556", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "fAFm4jkGNB1hsIr4o0S5hnhCCvY" + }, + "key": { + "$id": "557", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "WebDemo:Settings:BackgroundColor" + }, + "value": { + "$id": "558", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "blue" + }, + "tags": { + "$id": "559", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "560" + } + }, + "locked": { + "$id": "561", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "562", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-06-20T15:48:01+00:00" + } + } + } + ] + } + } + } + } + ] + } + ] + }, + { + "$id": "563", + "name": "checkKeyValues", + "resourceName": "AzureAppConfiguration", + "summary": "Requests the headers and status of the given resource.", + "doc": "Requests the headers and status of the given resource.", + "accessibility": "public", + "parameters": [ + { + "$id": "564", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "565", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "566", + "type": { + "$id": "567", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "568", + "name": "key", + "nameInRequest": "key", + "doc": "A filter used to match keys. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "569", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "570", + "name": "label", + "nameInRequest": "label", + "doc": "A filter used to match labels. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "571", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "572", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "573", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "574", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "575", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "576", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "577", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "578", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "579", + "kind": "array", + "name": "ArrayKeyValueFields", + "valueType": { + "$ref": "8" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "580", + "name": "snapshot", + "nameInRequest": "snapshot", + "doc": "A filter used get key-values for a snapshot. The value should be the name of\nthe snapshot. Not valid when used with 'key' and 'label' filters.", + "type": { + "$id": "581", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "582", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "583", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "584", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "585", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "586", + "name": "tags", + "nameInRequest": "tags", + "doc": "A filter used to query by tags. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "587", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "588", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": true, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "589", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "590", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "591", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "592", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "593", + "kind": "constant", + "valueType": { + "$id": "594", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "595", + "statusCodes": [ + 200 + ], + "headers": [ + { + "$id": "596", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "597", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "598", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "599", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "HEAD", + "uri": "{endpoint}", + "path": "/kv", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.checkKeyValues", + "decorators": [], + "examples": [ + { + "$id": "600", + "kind": "http", + "name": "Requests the headers and status of the given resource.", + "description": "Requests the headers and status of the given resource.", + "filePath": "2024-09-01/CheckKeyValues.json", + "parameters": [ + { + "$id": "601", + "parameter": { + "$ref": "564" + }, + "value": { + "$id": "602", + "kind": "string", + "type": { + "$ref": "565" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "603", + "response": { + "$ref": "595" + }, + "statusCode": 200 + } + ] + }, + { + "$id": "604", + "kind": "http", + "name": "Requests the headers and status of the given resource using the If-Match header.", + "description": "Requests the headers and status of the given resource using the If-Match header.", + "filePath": "2024-09-01/CheckKeyValues_IfMatch.json", + "parameters": [ + { + "$id": "605", + "parameter": { + "$ref": "564" + }, + "value": { + "$id": "606", + "kind": "string", + "type": { + "$ref": "565" + }, + "value": "2024-09-01" + } + }, + { + "$id": "607", + "parameter": { + "$ref": "582" + }, + "value": { + "$id": "608", + "kind": "string", + "type": { + "$ref": "583" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "609", + "response": { + "$ref": "595" + }, + "statusCode": 200 + } + ] + }, + { + "$id": "610", + "kind": "http", + "name": "Requests the headers and status of the given resource using the If-None-Match header.", + "description": "Requests the headers and status of the given resource using the If-None-Match header.", + "filePath": "2024-09-01/CheckKeyValues_IfNoneMatch.json", + "parameters": [ + { + "$id": "611", + "parameter": { + "$ref": "564" + }, + "value": { + "$id": "612", + "kind": "string", + "type": { + "$ref": "565" + }, + "value": "2024-09-01" + } + }, + { + "$id": "613", + "parameter": { + "$ref": "584" + }, + "value": { + "$id": "614", + "kind": "string", + "type": { + "$ref": "585" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "615", + "response": { + "$ref": "595" + }, + "statusCode": 200 + } + ] + } + ] + }, + { + "$id": "616", + "name": "getKeyValue", + "resourceName": "AzureAppConfiguration", + "summary": "Gets a single key-value.", + "doc": "Gets a single key-value.", + "accessibility": "public", + "parameters": [ + { + "$id": "617", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "618", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "619", + "type": { + "$id": "620", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "621", + "name": "key", + "nameInRequest": "key", + "doc": "The key of the key-value.", + "type": { + "$id": "622", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "623", + "name": "label", + "nameInRequest": "label", + "doc": "The label of the key-value to retrieve.", + "type": { + "$id": "624", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "625", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "626", + "kind": "array", + "name": "ArrayKeyValueFields", + "valueType": { + "$ref": "8" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "627", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "628", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "629", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "630", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "631", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "632", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "633", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "634", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "635", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "636", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "637", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "638", + "name": "tags", + "nameInRequest": "tags", + "doc": "A filter used to query by tags. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "639", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "640", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": true, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "641", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "642", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "643", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "182" + }, + "headers": [ + { + "$id": "644", + "name": "requestId", + "nameInResponse": "x-ms-request-id", + "doc": "An opaque, globally-unique, server-generated string identifier for the request.", + "type": { + "$id": "645", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "646", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + } + }, + { + "$id": "647", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "648", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "649", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "650", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "651", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "32" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.kv+json", + "application/problem+json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/kv/{key}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getKeyValue", + "decorators": [], + "examples": [ + { + "$id": "652", + "kind": "http", + "name": "Gets a single key-value.", + "description": "Gets a single key-value.", + "filePath": "2024-09-01/GetKeyValue.json", + "parameters": [ + { + "$id": "653", + "parameter": { + "$ref": "617" + }, + "value": { + "$id": "654", + "kind": "string", + "type": { + "$ref": "618" + }, + "value": "2024-09-01" + } + }, + { + "$id": "655", + "parameter": { + "$ref": "621" + }, + "value": { + "$id": "656", + "kind": "string", + "type": { + "$ref": "622" + }, + "value": "Message" + } + } + ], + "responses": [ + { + "$id": "657", + "response": { + "$ref": "643" + }, + "statusCode": 200, + "bodyValue": { + "$id": "658", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "659", + "etag": { + "$id": "660", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "7XpB48ET4VAlB9068ft6fKMyA3m" + }, + "key": { + "$id": "661", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "662", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "663", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "664" + } + }, + "locked": { + "$id": "665", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "666", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + }, + { + "$id": "667", + "kind": "http", + "name": "Gets a single key-value using the If-Match header.", + "description": "Gets a single key-value using the If-Match header.", + "filePath": "2024-09-01/GetKeyValue_IfMatch.json", + "parameters": [ + { + "$id": "668", + "parameter": { + "$ref": "617" + }, + "value": { + "$id": "669", + "kind": "string", + "type": { + "$ref": "618" + }, + "value": "2024-09-01" + } + }, + { + "$id": "670", + "parameter": { + "$ref": "621" + }, + "value": { + "$id": "671", + "kind": "string", + "type": { + "$ref": "622" + }, + "value": "Message" + } + }, + { + "$id": "672", + "parameter": { + "$ref": "631" + }, + "value": { + "$id": "673", + "kind": "string", + "type": { + "$ref": "632" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "674", + "response": { + "$ref": "643" + }, + "statusCode": 200, + "bodyValue": { + "$id": "675", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "676", + "etag": { + "$id": "677", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + }, + "key": { + "$id": "678", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "679", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "680", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "681" + } + }, + "locked": { + "$id": "682", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "683", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + }, + { + "$id": "684", + "kind": "http", + "name": "Gets a single key-value using the If-None-Match header.", + "description": "Gets a single key-value using the If-None-Match header.", + "filePath": "2024-09-01/GetKeyValue_IfNoneMatch.json", + "parameters": [ + { + "$id": "685", + "parameter": { + "$ref": "617" + }, + "value": { + "$id": "686", + "kind": "string", + "type": { + "$ref": "618" + }, + "value": "2024-09-01" + } + }, + { + "$id": "687", + "parameter": { + "$ref": "621" + }, + "value": { + "$id": "688", + "kind": "string", + "type": { + "$ref": "622" + }, + "value": "Message" + } + }, + { + "$id": "689", + "parameter": { + "$ref": "633" + }, + "value": { + "$id": "690", + "kind": "string", + "type": { + "$ref": "634" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + } + } + ], + "responses": [ + { + "$id": "691", + "response": { + "$ref": "643" + }, + "statusCode": 200, + "bodyValue": { + "$id": "692", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "693", + "etag": { + "$id": "694", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "7XpB48ET4VAlB9068ft6fKMyA3m" + }, + "key": { + "$id": "695", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "696", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "697", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "698" + } + }, + "locked": { + "$id": "699", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "700", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + } + ] + }, + { + "$id": "701", + "name": "putKeyValue", + "resourceName": "AzureAppConfiguration", + "summary": "Creates a key-value.", + "doc": "Creates a key-value.", + "accessibility": "public", + "parameters": [ + { + "$id": "702", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "703", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "704", + "type": { + "$id": "705", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "706", + "name": "contentType", + "nameInRequest": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "38" + }, + "location": "Header", + "isApiVersion": false, + "isContentType": true, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "707", + "name": "key", + "nameInRequest": "key", + "doc": "The key of the key-value to create.", + "type": { + "$id": "708", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "709", + "name": "label", + "nameInRequest": "label", + "doc": "The label of the key-value to create.", + "type": { + "$id": "710", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "711", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "712", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "713", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "714", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "715", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "716", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "717", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "718", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "719", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "720", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "721", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "722", + "name": "entity", + "nameInRequest": "entity", + "doc": "The key-value to create.", + "type": { + "$ref": "182" + }, + "location": "Body", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "723", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "182" + }, + "headers": [ + { + "$id": "724", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "725", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "726", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "727", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "728", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "32" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.kv+json", + "application/problem+json" + ] + } + ], + "httpMethod": "PUT", + "uri": "{endpoint}", + "path": "/kv/{key}", + "requestMediaTypes": [ + "application/vnd.microsoft.appconfig.kv+json", + "application/vnd.microsoft.appconfig.kvset+json", + "application/json", + "text/json", + "application/*+json", + "application/json-patch+json" + ], + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.putKeyValue", + "decorators": [], + "examples": [ + { + "$id": "729", + "kind": "http", + "name": "Creates a key-value.", + "description": "Creates a key-value.", + "filePath": "2024-09-01/PutKeyValue.json", + "parameters": [ + { + "$id": "730", + "parameter": { + "$ref": "702" + }, + "value": { + "$id": "731", + "kind": "string", + "type": { + "$ref": "703" + }, + "value": "2024-09-01" + } + }, + { + "$id": "732", + "parameter": { + "$ref": "707" + }, + "value": { + "$id": "733", + "kind": "string", + "type": { + "$ref": "708" + }, + "value": "Message" + } + } + ], + "responses": [ + { + "$id": "734", + "response": { + "$ref": "723" + }, + "statusCode": 200, + "bodyValue": { + "$id": "735", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "736", + "etag": { + "$id": "737", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "tnIHBkDYQwtdNMLoWtr5aybkKwL" + }, + "key": { + "$id": "738", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "739", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "740", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "741" + } + }, + "locked": { + "$id": "742", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "743", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + }, + { + "$id": "744", + "kind": "http", + "name": "Creates a key-value with the If-Match header.", + "description": "Creates a key-value with the If-Match header.", + "filePath": "2024-09-01/PutKeyValue_IfMatch.json", + "parameters": [ + { + "$id": "745", + "parameter": { + "$ref": "702" + }, + "value": { + "$id": "746", + "kind": "string", + "type": { + "$ref": "703" + }, + "value": "2024-09-01" + } + }, + { + "$id": "747", + "parameter": { + "$ref": "707" + }, + "value": { + "$id": "748", + "kind": "string", + "type": { + "$ref": "708" + }, + "value": "Message" + } + }, + { + "$id": "749", + "parameter": { + "$ref": "713" + }, + "value": { + "$id": "750", + "kind": "string", + "type": { + "$ref": "714" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "751", + "response": { + "$ref": "723" + }, + "statusCode": 200, + "bodyValue": { + "$id": "752", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "753", + "etag": { + "$id": "754", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + }, + "key": { + "$id": "755", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "756", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "757", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "758" + } + }, + "locked": { + "$id": "759", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "760", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + } + ] + }, + { + "$id": "761", + "name": "deleteKeyValue", + "resourceName": "AzureAppConfiguration", + "summary": "Deletes a key-value.", + "doc": "Deletes a key-value.", + "accessibility": "public", + "parameters": [ + { + "$id": "762", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "763", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "764", + "type": { + "$id": "765", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "766", + "name": "key", + "nameInRequest": "key", + "doc": "The key of the key-value to delete.", + "type": { + "$id": "767", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "768", + "name": "label", + "nameInRequest": "label", + "doc": "The label of the key-value to delete.", + "type": { + "$id": "769", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "770", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "771", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "772", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "773", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "774", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "775", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "776", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "777", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "778", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "779", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "182" + }, + "headers": [ + { + "$id": "780", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "781", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "782", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "783", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "784", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "32" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.kv+json", + "application/problem+json" + ] + }, + { + "$id": "785", + "statusCodes": [ + 204 + ], + "headers": [ + { + "$id": "786", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "787", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "DELETE", + "uri": "{endpoint}", + "path": "/kv/{key}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.deleteKeyValue", + "decorators": [], + "examples": [ + { + "$id": "788", + "kind": "http", + "name": "Deletes a key-value.", + "description": "Deletes a key-value.", + "filePath": "2024-09-01/DeleteKeyValue.json", + "parameters": [ + { + "$id": "789", + "parameter": { + "$ref": "762" + }, + "value": { + "$id": "790", + "kind": "string", + "type": { + "$ref": "763" + }, + "value": "2024-09-01" + } + }, + { + "$id": "791", + "parameter": { + "$ref": "766" + }, + "value": { + "$id": "792", + "kind": "string", + "type": { + "$ref": "767" + }, + "value": "Message" + } + } + ], + "responses": [ + { + "$id": "793", + "response": { + "$ref": "779" + }, + "statusCode": 200, + "bodyValue": { + "$id": "794", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "795", + "etag": { + "$id": "796", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "7XpB48ET4VAlB9068ft6fKMyA3m" + }, + "key": { + "$id": "797", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "798", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "799", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "800" + } + }, + "locked": { + "$id": "801", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "802", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + }, + { + "$id": "803", + "response": { + "$ref": "785" + }, + "statusCode": 204 + } + ] + }, + { + "$id": "804", + "kind": "http", + "name": "Deletes a key-value using If-Match header", + "description": "Deletes a key-value using If-Match header", + "filePath": "2024-09-01/DeleteKeyValue_IfMatch.json", + "parameters": [ + { + "$id": "805", + "parameter": { + "$ref": "762" + }, + "value": { + "$id": "806", + "kind": "string", + "type": { + "$ref": "763" + }, + "value": "2024-09-01" + } + }, + { + "$id": "807", + "parameter": { + "$ref": "766" + }, + "value": { + "$id": "808", + "kind": "string", + "type": { + "$ref": "767" + }, + "value": "Message" + } + }, + { + "$id": "809", + "parameter": { + "$ref": "772" + }, + "value": { + "$id": "810", + "kind": "string", + "type": { + "$ref": "773" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "811", + "response": { + "$ref": "779" + }, + "statusCode": 200, + "bodyValue": { + "$id": "812", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "813", + "etag": { + "$id": "814", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + }, + "key": { + "$id": "815", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "816", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "817", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "818" + } + }, + "locked": { + "$id": "819", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "820", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + }, + { + "$id": "821", + "response": { + "$ref": "785" + }, + "statusCode": 204 + } + ] + } + ] + }, + { + "$id": "822", + "name": "checkKeyValue", + "resourceName": "AzureAppConfiguration", + "summary": "Requests the headers and status of the given resource.", + "doc": "Requests the headers and status of the given resource.", + "accessibility": "public", + "parameters": [ + { + "$id": "823", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "824", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "825", + "type": { + "$id": "826", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "827", + "name": "key", + "nameInRequest": "key", + "doc": "The key of the key-value to retrieve.", + "type": { + "$id": "828", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "829", + "name": "label", + "nameInRequest": "label", + "doc": "The label of the key-value to retrieve.", + "type": { + "$id": "830", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "831", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "832", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "833", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "834", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "835", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "836", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "837", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "838", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "839", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "840", + "kind": "array", + "name": "ArrayKeyValueFields", + "valueType": { + "$ref": "8" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "841", + "name": "tags", + "nameInRequest": "tags", + "doc": "A filter used to query by tags. Syntax reference:\nhttps://aka.ms/azconfig/docs/keyvaluefiltering", + "type": { + "$id": "842", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "843", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": true, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "844", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "845", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "846", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "847", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "848", + "kind": "constant", + "valueType": { + "$id": "849", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "850", + "statusCodes": [ + 200 + ], + "headers": [ + { + "$id": "851", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "852", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "853", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "854", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "HEAD", + "uri": "{endpoint}", + "path": "/kv/{key}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.checkKeyValue", + "decorators": [], + "examples": [ + { + "$id": "855", + "kind": "http", + "name": "Requests the headers and status of the given resource.", + "description": "Requests the headers and status of the given resource.", + "filePath": "2024-09-01/CheckKeyValue.json", + "parameters": [ + { + "$id": "856", + "parameter": { + "$ref": "823" + }, + "value": { + "$id": "857", + "kind": "string", + "type": { + "$ref": "824" + }, + "value": "2024-09-01" + } + }, + { + "$id": "858", + "parameter": { + "$ref": "827" + }, + "value": { + "$id": "859", + "kind": "string", + "type": { + "$ref": "828" + }, + "value": "Message" + } + } + ], + "responses": [ + { + "$id": "860", + "response": { + "$ref": "850" + }, + "statusCode": 200 + } + ] + }, + { + "$id": "861", + "kind": "http", + "name": "Requests the headers and status of the given resource using the If-Match header.", + "description": "Requests the headers and status of the given resource using the If-Match header.", + "filePath": "2024-09-01/CheckKeyValue_IfMatch.json", + "parameters": [ + { + "$id": "862", + "parameter": { + "$ref": "823" + }, + "value": { + "$id": "863", + "kind": "string", + "type": { + "$ref": "824" + }, + "value": "2024-09-01" + } + }, + { + "$id": "864", + "parameter": { + "$ref": "827" + }, + "value": { + "$id": "865", + "kind": "string", + "type": { + "$ref": "828" + }, + "value": "Message" + } + }, + { + "$id": "866", + "parameter": { + "$ref": "835" + }, + "value": { + "$id": "867", + "kind": "string", + "type": { + "$ref": "836" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "868", + "response": { + "$ref": "850" + }, + "statusCode": 200 + } + ] + }, + { + "$id": "869", + "kind": "http", + "name": "Requests the headers and status of the given resource using the If-None-Match header.", + "description": "Requests the headers and status of the given resource using the If-None-Match header.", + "filePath": "2024-09-01/CheckKeyValue_IfNoneMatch.json", + "parameters": [ + { + "$id": "870", + "parameter": { + "$ref": "823" + }, + "value": { + "$id": "871", + "kind": "string", + "type": { + "$ref": "824" + }, + "value": "2024-09-01" + } + }, + { + "$id": "872", + "parameter": { + "$ref": "827" + }, + "value": { + "$id": "873", + "kind": "string", + "type": { + "$ref": "828" + }, + "value": "Message" + } + }, + { + "$id": "874", + "parameter": { + "$ref": "837" + }, + "value": { + "$id": "875", + "kind": "string", + "type": { + "$ref": "838" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + } + } + ], + "responses": [ + { + "$id": "876", + "response": { + "$ref": "850" + }, + "statusCode": 200 + } + ] + } + ] + }, + { + "$id": "877", + "name": "getSnapshots", + "resourceName": "Snapshot", + "summary": "Gets a list of key-value snapshots.", + "doc": "Gets a list of key-value snapshots.", + "accessibility": "public", + "parameters": [ + { + "$id": "878", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "879", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "880", + "type": { + "$id": "881", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "882", + "name": "name", + "nameInRequest": "name", + "doc": "A filter for the name of the returned snapshots.", + "type": { + "$id": "883", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "884", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "885", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "886", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "887", + "kind": "array", + "name": "ArraySnapshotFields", + "valueType": { + "$ref": "52" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "888", + "name": "status", + "nameInRequest": "status", + "doc": "Used to filter returned snapshots by their status property.", + "type": { + "$id": "889", + "kind": "array", + "name": "ArraySnapshotStatus", + "valueType": { + "$ref": "76" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "890", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "891", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "892", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "893", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "894", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "228" + }, + "headers": [ + { + "$id": "895", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "896", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "897", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "92" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.snapshotset+json", + "application/problem+json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/snapshots", + "bufferResponse": true, + "paging": { + "$id": "898", + "itemPropertySegments": [ + "items" + ], + "nextLink": { + "$id": "899", + "responseSegments": [ + "@nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getSnapshots", + "decorators": [], + "examples": [ + { + "$id": "900", + "kind": "http", + "name": "Gets a list of key-value snapshots.", + "description": "Gets a list of key-value snapshots.", + "filePath": "2024-09-01/GetSnapshots.json", + "parameters": [ + { + "$id": "901", + "parameter": { + "$ref": "878" + }, + "value": { + "$id": "902", + "kind": "string", + "type": { + "$ref": "879" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "903", + "response": { + "$ref": "894" + }, + "statusCode": 200, + "bodyValue": { + "$id": "904", + "kind": "model", + "type": { + "$ref": "228" + }, + "value": { + "$id": "905", + "items": { + "$id": "906", + "kind": "array", + "type": { + "$ref": "230" + }, + "value": [ + { + "$id": "907", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "908", + "etag": { + "$id": "909", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "910", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "911", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "ready" + }, + "filters": { + "$id": "912", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "913", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "914", + "key": { + "$id": "915", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "916", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "917", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "918", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "size": { + "$id": "919", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 100000 + }, + "items_count": { + "$id": "920", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 71 + }, + "retention_period": { + "$id": "921", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 2592000 + }, + "tags": { + "$id": "922", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "923", + "release": { + "$id": "924", + "kind": "string", + "type": { + "$ref": "285" + }, + "value": "{link/id}" + } + } + } + } + } + ] + } + } + } + } + ] + } + ] + }, + { + "$id": "925", + "name": "checkSnapshots", + "resourceName": "AzureAppConfiguration", + "summary": "Requests the headers and status of the given resource.", + "doc": "Requests the headers and status of the given resource.", + "accessibility": "public", + "parameters": [ + { + "$id": "926", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "927", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "928", + "type": { + "$id": "929", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "930", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "931", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "932", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "933", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "934", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "935", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "936", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "937", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "938", + "kind": "constant", + "valueType": { + "$id": "939", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "940", + "statusCodes": [ + 200 + ], + "headers": [ + { + "$id": "941", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "942", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "HEAD", + "uri": "{endpoint}", + "path": "/snapshots", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.checkSnapshots", + "decorators": [], + "examples": [ + { + "$id": "943", + "kind": "http", + "name": "Requests the headers and status of the given resource.", + "description": "Requests the headers and status of the given resource.", + "filePath": "2024-09-01/CheckSnapshots.json", + "parameters": [ + { + "$id": "944", + "parameter": { + "$ref": "926" + }, + "value": { + "$id": "945", + "kind": "string", + "type": { + "$ref": "927" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "946", + "response": { + "$ref": "940" + }, + "statusCode": 200 + } + ] + } + ] + }, + { + "$id": "947", + "name": "getSnapshot", + "resourceName": "Snapshot", + "summary": "Gets a single key-value snapshot.", + "doc": "Gets a single key-value snapshot.", + "accessibility": "public", + "parameters": [ + { + "$id": "948", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "949", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "950", + "type": { + "$id": "951", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "952", + "name": "name", + "nameInRequest": "name", + "doc": "The name of the snapshot.", + "type": { + "$id": "953", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "954", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "955", + "kind": "array", + "name": "ArraySnapshotFields", + "valueType": { + "$ref": "52" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "956", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "957", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "958", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "959", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "960", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "961", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "962", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "963", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "964", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "965", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "966", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "967", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "231" + }, + "headers": [ + { + "$id": "968", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "969", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "970", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "971", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "972", + "name": "link", + "nameInResponse": "Link", + "doc": "Includes links to related resources.", + "type": { + "$id": "973", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "974", + "name": "requestId", + "nameInResponse": "x-ms-request-id", + "doc": "An opaque, globally-unique, server-generated string identifier for the request.", + "type": { + "$id": "975", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "976", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + } + }, + { + "$id": "977", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "98" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.snapshot+json", + "application/problem+json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/snapshots/{name}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getSnapshot", + "decorators": [], + "examples": [ + { + "$id": "978", + "kind": "http", + "name": "Gets a single key-value snapshot.", + "description": "Gets a single key-value snapshot.", + "filePath": "2024-09-01/GetSnapshot.json", + "parameters": [ + { + "$id": "979", + "parameter": { + "$ref": "948" + }, + "value": { + "$id": "980", + "kind": "string", + "type": { + "$ref": "949" + }, + "value": "2024-09-01" + } + }, + { + "$id": "981", + "parameter": { + "$ref": "952" + }, + "value": { + "$id": "982", + "kind": "string", + "type": { + "$ref": "953" + }, + "value": "Prod-2022-08-01" + } + } + ], + "responses": [ + { + "$id": "983", + "response": { + "$ref": "967" + }, + "statusCode": 200, + "bodyValue": { + "$id": "984", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "985", + "etag": { + "$id": "986", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "987", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "988", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "ready" + }, + "filters": { + "$id": "989", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "990", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "991", + "key": { + "$id": "992", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "993", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "994", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "995", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "size": { + "$id": "996", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 100000 + }, + "items_count": { + "$id": "997", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 71 + }, + "retention_period": { + "$id": "998", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 2592000 + }, + "tags": { + "$id": "999", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "1000", + "release": { + "$id": "1001", + "kind": "string", + "type": { + "$ref": "285" + }, + "value": "{link/id}" + } + } + } + } + } + } + ] + }, + { + "$id": "1002", + "kind": "http", + "name": "Gets a single key-value snapshot failed.", + "description": "Gets a single key-value snapshot failed.", + "filePath": "2024-09-01/GetSnapshot_Failed.json", + "parameters": [ + { + "$id": "1003", + "parameter": { + "$ref": "948" + }, + "value": { + "$id": "1004", + "kind": "string", + "type": { + "$ref": "949" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1005", + "parameter": { + "$ref": "952" + }, + "value": { + "$id": "1006", + "kind": "string", + "type": { + "$ref": "953" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1007", + "parameter": { + "$ref": "958" + }, + "value": { + "$id": "1008", + "kind": "string", + "type": { + "$ref": "959" + }, + "value": "\"4f6dd610dd5e4deebc7fbaef685fb903\"" + } + } + ], + "responses": [ + { + "$id": "1009", + "response": { + "$ref": "967" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1010", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "1011", + "etag": { + "$id": "1012", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "1013", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "1014", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "failed" + }, + "filters": { + "$id": "1015", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "1016", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "1017", + "key": { + "$id": "1018", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "1019", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "1020", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "1021", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "size": { + "$id": "1022", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 0 + }, + "items_count": { + "$id": "1023", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 0 + }, + "retention_period": { + "$id": "1024", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 2592000 + }, + "tags": { + "$id": "1025", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "1026", + "release": { + "$id": "1027", + "kind": "string", + "type": { + "$ref": "285" + }, + "value": "{link/id}" + } + } + } + } + } + } + ] + }, + { + "$id": "1028", + "kind": "http", + "name": "Gets a single key-value snapshot using If-Match header.", + "description": "Gets a single key-value snapshot using If-Match header.", + "filePath": "2024-09-01/GetSnapshot_IfMatch.json", + "parameters": [ + { + "$id": "1029", + "parameter": { + "$ref": "948" + }, + "value": { + "$id": "1030", + "kind": "string", + "type": { + "$ref": "949" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1031", + "parameter": { + "$ref": "952" + }, + "value": { + "$id": "1032", + "kind": "string", + "type": { + "$ref": "953" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1033", + "parameter": { + "$ref": "958" + }, + "value": { + "$id": "1034", + "kind": "string", + "type": { + "$ref": "959" + }, + "value": "\"4f6dd610dd5e4deebc7fbaef685fb903\"" + } + } + ], + "responses": [ + { + "$id": "1035", + "response": { + "$ref": "967" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1036", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "1037", + "etag": { + "$id": "1038", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "1039", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "1040", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "ready" + }, + "filters": { + "$id": "1041", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "1042", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "1043", + "key": { + "$id": "1044", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "1045", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "1046", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "1047", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "size": { + "$id": "1048", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 100000 + }, + "items_count": { + "$id": "1049", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 71 + }, + "retention_period": { + "$id": "1050", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 2592000 + }, + "tags": { + "$id": "1051", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "1052", + "release": { + "$id": "1053", + "kind": "string", + "type": { + "$ref": "285" + }, + "value": "{link/id}" + } + } + } + } + } + } + ] + }, + { + "$id": "1054", + "kind": "http", + "name": "Gets a single key-value snapshot using If-None-Match header.", + "description": "Gets a single key-value snapshot using If-None-Match header.", + "filePath": "2024-09-01/GetSnapshot_IfNoneMatch.json", + "parameters": [ + { + "$id": "1055", + "parameter": { + "$ref": "948" + }, + "value": { + "$id": "1056", + "kind": "string", + "type": { + "$ref": "949" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1057", + "parameter": { + "$ref": "952" + }, + "value": { + "$id": "1058", + "kind": "string", + "type": { + "$ref": "953" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1059", + "parameter": { + "$ref": "960" + }, + "value": { + "$id": "1060", + "kind": "string", + "type": { + "$ref": "961" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "1061", + "response": { + "$ref": "967" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1062", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "1063", + "etag": { + "$id": "1064", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "1065", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "1066", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "ready" + }, + "filters": { + "$id": "1067", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "1068", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "1069", + "key": { + "$id": "1070", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "1071", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "1072", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "1073", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "size": { + "$id": "1074", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 100000 + }, + "items_count": { + "$id": "1075", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 71 + }, + "retention_period": { + "$id": "1076", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 2592000 + }, + "tags": { + "$id": "1077", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "1078", + "release": { + "$id": "1079", + "kind": "string", + "type": { + "$ref": "285" + }, + "value": "{link/id}" + } + } + } + } + } + } + ] + } + ] + }, + { + "$id": "1080", + "name": "getOperationDetails", + "resourceName": "AzureAppConfiguration", + "summary": "Gets the state of a long running operation.", + "doc": "Gets the state of a long running operation.", + "accessibility": "public", + "parameters": [ + { + "$id": "1081", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1082", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1083", + "type": { + "$id": "1084", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1085", + "name": "snapshot", + "nameInRequest": "snapshot", + "doc": "Snapshot identifier for the long running operation.", + "type": { + "$id": "1086", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1087", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1088", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1089", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1090", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1091", + "kind": "constant", + "valueType": { + "$id": "1092", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1093", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "298" + }, + "headers": [], + "isErrorResponse": false, + "contentTypes": [ + "application/json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/operations", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getOperationDetails", + "decorators": [], + "examples": [ + { + "$id": "1094", + "kind": "http", + "name": "Gets the state of a long running operation.", + "description": "Gets the state of a long running operation.", + "filePath": "2024-09-01/GetOperationStatus.json", + "parameters": [ + { + "$id": "1095", + "parameter": { + "$ref": "1081" + }, + "value": { + "$id": "1096", + "kind": "string", + "type": { + "$ref": "1082" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1097", + "parameter": { + "$ref": "1085" + }, + "value": { + "$id": "1098", + "kind": "string", + "type": { + "$ref": "1086" + }, + "value": "Prod-2022-08-01" + } + } + ], + "responses": [ + { + "$id": "1099", + "response": { + "$ref": "1093" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1100", + "kind": "model", + "type": { + "$ref": "298" + }, + "value": { + "$id": "1101", + "id": { + "$id": "1102", + "kind": "string", + "type": { + "$ref": "300" + }, + "value": "4yghgV_8lJJ5t7_kxhMpsyNCyjmZE5Q6zU0pXOp7Jvs" + }, + "status": { + "$id": "1103", + "kind": "string", + "type": { + "$ref": "104" + }, + "value": "Running" + } + } + } + } + ] + } + ] + }, + { + "$id": "1104", + "name": "createSnapshot", + "resourceName": "Snapshot", + "summary": "Creates a key-value snapshot.", + "doc": "Creates a key-value snapshot.", + "accessibility": "public", + "parameters": [ + { + "$id": "1105", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1106", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1107", + "type": { + "$id": "1108", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1109", + "name": "contentType", + "nameInRequest": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "116" + }, + "location": "Header", + "isApiVersion": false, + "isContentType": true, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1110", + "name": "name", + "nameInRequest": "name", + "doc": "The name of the key-value snapshot to create.", + "type": { + "$id": "1111", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1112", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1113", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1114", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1115", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1116", + "name": "entity", + "nameInRequest": "entity", + "doc": "The key-value snapshot to create.", + "type": { + "$ref": "231" + }, + "location": "Body", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1117", + "statusCodes": [ + 201 + ], + "bodyType": { + "$ref": "231" + }, + "headers": [ + { + "$id": "1118", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1119", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1120", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "1121", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1122", + "name": "link", + "nameInResponse": "Link", + "doc": "Includes links to related resources.", + "type": { + "$id": "1123", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1124", + "name": "operationLocation", + "nameInResponse": "Operation-Location", + "doc": "The location for monitoring the operation state.", + "type": { + "$id": "1125", + "kind": "url", + "name": "ResourceLocation", + "crossLanguageDefinitionId": "TypeSpec.Rest.ResourceLocation", + "baseType": { + "$id": "1126", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url", + "decorators": [] + }, + "decorators": [] + } + }, + { + "$id": "1127", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "98" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.snapshot+json", + "application/problem+json" + ] + } + ], + "httpMethod": "PUT", + "uri": "{endpoint}", + "path": "/snapshots/{name}", + "requestMediaTypes": [ + "application/vnd.microsoft.appconfig.snapshot+json", + "application/json" + ], + "bufferResponse": true, + "longRunning": { + "$id": "1128", + "finalStateVia": 2, + "finalResponse": { + "$id": "1129", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "231" + } + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.createSnapshot", + "decorators": [], + "examples": [ + { + "$id": "1130", + "kind": "http", + "name": "Creates a key-value snapshot.", + "description": "Creates a key-value snapshot.", + "filePath": "2024-09-01/CreateSnapshot.json", + "parameters": [ + { + "$id": "1131", + "parameter": { + "$ref": "1105" + }, + "value": { + "$id": "1132", + "kind": "string", + "type": { + "$ref": "1106" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1133", + "parameter": { + "$ref": "1110" + }, + "value": { + "$id": "1134", + "kind": "string", + "type": { + "$ref": "1111" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1135", + "parameter": { + "$ref": "1116" + }, + "value": { + "$id": "1136", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "1137", + "filters": { + "$id": "1138", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "1139", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "1140", + "key": { + "$id": "1141", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "1142", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "retention_period": { + "$id": "1143", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 3600 + } + } + } + } + ], + "responses": [ + { + "$id": "1144", + "response": { + "$ref": "1117" + }, + "statusCode": 201, + "bodyValue": { + "$id": "1145", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "1146", + "etag": { + "$id": "1147", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "1148", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "1149", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "provisioning" + }, + "filters": { + "$id": "1150", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "1151", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "1152", + "key": { + "$id": "1153", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "1154", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "1155", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "1156", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "size": { + "$id": "1157", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 0 + }, + "items_count": { + "$id": "1158", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 0 + }, + "retention_period": { + "$id": "1159", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 3600 + }, + "tags": { + "$id": "1160", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "1161" + } + } + } + } + } + ] + } + ] + }, + { + "$id": "1162", + "name": "updateSnapshot", + "resourceName": "AzureAppConfiguration", + "summary": "Updates the state of a key-value snapshot.", + "doc": "Updates the state of a key-value snapshot.", + "accessibility": "public", + "parameters": [ + { + "$id": "1163", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1164", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1165", + "type": { + "$id": "1166", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1167", + "name": "contentType", + "nameInRequest": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "122" + }, + "location": "Header", + "isApiVersion": false, + "isContentType": true, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1168", + "name": "name", + "nameInRequest": "name", + "doc": "The name of the key-value snapshot to update.", + "type": { + "$id": "1169", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1170", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1171", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1172", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "1173", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1174", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "1175", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1176", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1177", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1178", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1179", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1180", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1181", + "name": "entity", + "nameInRequest": "entity", + "doc": "The parameters used to update the snapshot.", + "type": { + "$ref": "309" + }, + "location": "Body", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1182", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "231" + }, + "headers": [ + { + "$id": "1183", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1184", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1185", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "1186", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1187", + "name": "link", + "nameInResponse": "Link", + "doc": "Includes links to related resources.", + "type": { + "$id": "1188", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1189", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "98" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.snapshot+json", + "application/problem+json" + ] + } + ], + "httpMethod": "PATCH", + "uri": "{endpoint}", + "path": "/snapshots/{name}", + "requestMediaTypes": [ + "application/merge-patch+json", + "application/json" + ], + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": false, + "crossLanguageDefinitionId": "AzureAppConfiguration.updateSnapshot", + "decorators": [], + "examples": [ + { + "$id": "1190", + "kind": "http", + "name": "Updates the state of a key-value snapshot.", + "description": "Updates the state of a key-value snapshot.", + "filePath": "2024-09-01/UpdateSnapshot.json", + "parameters": [ + { + "$id": "1191", + "parameter": { + "$ref": "1163" + }, + "value": { + "$id": "1192", + "kind": "string", + "type": { + "$ref": "1164" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1193", + "parameter": { + "$ref": "1168" + }, + "value": { + "$id": "1194", + "kind": "string", + "type": { + "$ref": "1169" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1195", + "parameter": { + "$ref": "1181" + }, + "value": { + "$id": "1196", + "kind": "model", + "type": { + "$ref": "309" + }, + "value": { + "$id": "1197", + "status": { + "$id": "1198", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "archived" + } + } + } + } + ], + "responses": [ + { + "$id": "1199", + "response": { + "$ref": "1182" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1200", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "1201", + "etag": { + "$id": "1202", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "1203", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "1204", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "archived" + }, + "filters": { + "$id": "1205", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "1206", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "1207", + "key": { + "$id": "1208", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "1209", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "1210", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "1211", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "expires": { + "$id": "1212", + "kind": "string", + "type": { + "$ref": "266" + }, + "value": "2022-09-01T22:19:40+00:00" + }, + "size": { + "$id": "1213", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 10000 + }, + "items_count": { + "$id": "1214", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 70 + }, + "retention_period": { + "$id": "1215", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 2592000 + }, + "tags": { + "$id": "1216", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "1217" + } + } + } + } + } + ] + }, + { + "$id": "1218", + "kind": "http", + "name": "Updates the state of a key-value snapshot using the If-Match header.", + "description": "Updates the state of a key-value snapshot using the If-Match header.", + "filePath": "2024-09-01/UpdateSnapshot_IfMatch.json", + "parameters": [ + { + "$id": "1219", + "parameter": { + "$ref": "1163" + }, + "value": { + "$id": "1220", + "kind": "string", + "type": { + "$ref": "1164" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1221", + "parameter": { + "$ref": "1168" + }, + "value": { + "$id": "1222", + "kind": "string", + "type": { + "$ref": "1169" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1223", + "parameter": { + "$ref": "1181" + }, + "value": { + "$id": "1224", + "kind": "model", + "type": { + "$ref": "309" + }, + "value": { + "$id": "1225", + "status": { + "$id": "1226", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "archived" + } + } + } + }, + { + "$id": "1227", + "parameter": { + "$ref": "1172" + }, + "value": { + "$id": "1228", + "kind": "string", + "type": { + "$ref": "1173" + }, + "value": "\"4f6dd610dd5e4deebc7fbaef685fb903\"" + } + } + ], + "responses": [ + { + "$id": "1229", + "response": { + "$ref": "1182" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1230", + "kind": "model", + "type": { + "$ref": "231" + }, + "value": { + "$id": "1231", + "etag": { + "$id": "1232", + "kind": "string", + "type": { + "$ref": "289" + }, + "value": "4f6dd610dd5e4deebc7fbaef685fb903" + }, + "name": { + "$id": "1233", + "kind": "string", + "type": { + "$ref": "233" + }, + "value": "Prod-2022-08-01" + }, + "status": { + "$id": "1234", + "kind": "string", + "type": { + "$ref": "76" + }, + "value": "archived" + }, + "filters": { + "$id": "1235", + "kind": "array", + "type": { + "$ref": "240" + }, + "value": [ + { + "$id": "1236", + "kind": "model", + "type": { + "$ref": "241" + }, + "value": { + "$id": "1237", + "key": { + "$id": "1238", + "kind": "string", + "type": { + "$ref": "243" + }, + "value": "app1/*" + }, + "label": { + "$id": "1239", + "kind": "string", + "type": { + "$ref": "247" + }, + "value": "Production" + } + } + } + ] + }, + "composition_type": { + "$id": "1240", + "kind": "string", + "type": { + "$ref": "86" + }, + "value": "all" + }, + "created": { + "$id": "1241", + "kind": "string", + "type": { + "$ref": "261" + }, + "value": "2022-08-01T22:19:40+00:00" + }, + "expires": { + "$id": "1242", + "kind": "string", + "type": { + "$ref": "266" + }, + "value": "2022-09-01T22:19:40+00:00" + }, + "size": { + "$id": "1243", + "kind": "number", + "type": { + "$ref": "275" + }, + "value": 10000 + }, + "items_count": { + "$id": "1244", + "kind": "number", + "type": { + "$ref": "279" + }, + "value": 70 + }, + "retention_period": { + "$id": "1245", + "kind": "number", + "type": { + "$ref": "271" + }, + "value": 2592000 + }, + "tags": { + "$id": "1246", + "kind": "dict", + "type": { + "$ref": "283" + }, + "value": { + "$id": "1247" + } + } + } + } + } + ] + } + ] + }, + { + "$id": "1248", + "name": "checkSnapshot", + "resourceName": "AzureAppConfiguration", + "summary": "Requests the headers and status of the given resource.", + "doc": "Requests the headers and status of the given resource.", + "accessibility": "public", + "parameters": [ + { + "$id": "1249", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1250", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1251", + "type": { + "$id": "1252", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1253", + "name": "name", + "nameInRequest": "name", + "doc": "The name of the key-value snapshot to check.", + "type": { + "$id": "1254", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1255", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1256", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1257", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "1258", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1259", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "1260", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1261", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1262", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1263", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1264", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1265", + "kind": "constant", + "valueType": { + "$id": "1266", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1267", + "statusCodes": [ + 200 + ], + "headers": [ + { + "$id": "1268", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1269", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1270", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "1271", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1272", + "name": "link", + "nameInResponse": "Link", + "doc": "Includes links to related resources.", + "type": { + "$id": "1273", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "HEAD", + "uri": "{endpoint}", + "path": "/snapshots/{name}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.checkSnapshot", + "decorators": [], + "examples": [ + { + "$id": "1274", + "kind": "http", + "name": "Requests the headers and status of the given resource.", + "description": "Requests the headers and status of the given resource.", + "filePath": "2024-09-01/CheckSnapshot.json", + "parameters": [ + { + "$id": "1275", + "parameter": { + "$ref": "1249" + }, + "value": { + "$id": "1276", + "kind": "string", + "type": { + "$ref": "1250" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1277", + "parameter": { + "$ref": "1253" + }, + "value": { + "$id": "1278", + "kind": "string", + "type": { + "$ref": "1254" + }, + "value": "Prod-2022-08-01" + } + } + ], + "responses": [ + { + "$id": "1279", + "response": { + "$ref": "1267" + }, + "statusCode": 200 + } + ] + }, + { + "$id": "1280", + "kind": "http", + "name": "Requests the headers and status of the given resource using If-Match header.", + "description": "Requests the headers and status of the given resource using If-Match header.", + "filePath": "2024-09-01/CheckSnapshot_IfMatch.json", + "parameters": [ + { + "$id": "1281", + "parameter": { + "$ref": "1249" + }, + "value": { + "$id": "1282", + "kind": "string", + "type": { + "$ref": "1250" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1283", + "parameter": { + "$ref": "1253" + }, + "value": { + "$id": "1284", + "kind": "string", + "type": { + "$ref": "1254" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1285", + "parameter": { + "$ref": "1257" + }, + "value": { + "$id": "1286", + "kind": "string", + "type": { + "$ref": "1258" + }, + "value": "\"4f6dd610dd5e4deebc7fbaef685fb903\"" + } + } + ], + "responses": [ + { + "$id": "1287", + "response": { + "$ref": "1267" + }, + "statusCode": 200 + } + ] + }, + { + "$id": "1288", + "kind": "http", + "name": "Requests the headers and status of the given resource using If-None-Match header", + "description": "Requests the headers and status of the given resource using If-None-Match header", + "filePath": "2024-09-01/CheckSnapshot_IfNoneMatch.json", + "parameters": [ + { + "$id": "1289", + "parameter": { + "$ref": "1249" + }, + "value": { + "$id": "1290", + "kind": "string", + "type": { + "$ref": "1250" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1291", + "parameter": { + "$ref": "1253" + }, + "value": { + "$id": "1292", + "kind": "string", + "type": { + "$ref": "1254" + }, + "value": "Prod-2022-08-01" + } + }, + { + "$id": "1293", + "parameter": { + "$ref": "1259" + }, + "value": { + "$id": "1294", + "kind": "string", + "type": { + "$ref": "1260" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "1295", + "response": { + "$ref": "1267" + }, + "statusCode": 200 + } + ] + } + ] + }, + { + "$id": "1296", + "name": "getLabels", + "resourceName": "AzureAppConfiguration", + "summary": "Gets a list of labels.", + "doc": "Gets a list of labels.", + "accessibility": "public", + "parameters": [ + { + "$id": "1297", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1298", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1299", + "type": { + "$id": "1300", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1301", + "name": "name", + "nameInRequest": "name", + "doc": "A filter for the name of the returned labels.", + "type": { + "$id": "1302", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1303", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1304", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1305", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "1306", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1307", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "1308", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1309", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "1310", + "kind": "array", + "name": "ArrayLabelFields", + "valueType": { + "$ref": "128" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1311", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1312", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1313", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1314", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1315", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1316", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "313" + }, + "headers": [ + { + "$id": "1317", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1318", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1319", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "132" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.labelset+json", + "application/problem+json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/labels", + "bufferResponse": true, + "paging": { + "$id": "1320", + "itemPropertySegments": [ + "items" + ], + "nextLink": { + "$id": "1321", + "responseSegments": [ + "@nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getLabels", + "decorators": [], + "examples": [ + { + "$id": "1322", + "kind": "http", + "name": "Gets a list of labels.", + "description": "Gets a list of labels.", + "filePath": "2024-09-01/GetLabels.json", + "parameters": [ + { + "$id": "1323", + "parameter": { + "$ref": "1297" + }, + "value": { + "$id": "1324", + "kind": "string", + "type": { + "$ref": "1298" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "1325", + "response": { + "$ref": "1316" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1326", + "kind": "model", + "type": { + "$ref": "313" + }, + "value": { + "$id": "1327", + "items": { + "$id": "1328", + "kind": "array", + "type": { + "$ref": "315" + }, + "value": [ + { + "$id": "1329", + "kind": "model", + "type": { + "$ref": "316" + }, + "value": { + "$id": "1330" + } + }, + { + "$id": "1331", + "kind": "model", + "type": { + "$ref": "316" + }, + "value": { + "$id": "1332", + "name": { + "$id": "1333", + "kind": "string", + "type": { + "$ref": "318" + }, + "value": "Asset1" + } + } + }, + { + "$id": "1334", + "kind": "model", + "type": { + "$ref": "316" + }, + "value": { + "$id": "1335", + "name": { + "$id": "1336", + "kind": "string", + "type": { + "$ref": "318" + }, + "value": "Asset1/devCi" + } + } + }, + { + "$id": "1337", + "kind": "model", + "type": { + "$ref": "316" + }, + "value": { + "$id": "1338", + "name": { + "$id": "1339", + "kind": "string", + "type": { + "$ref": "318" + }, + "value": "Asset1/devCi/branch1" + } + } + }, + { + "$id": "1340", + "kind": "model", + "type": { + "$ref": "316" + }, + "value": { + "$id": "1341", + "name": { + "$id": "1342", + "kind": "string", + "type": { + "$ref": "318" + }, + "value": "WestUs" + } + } + } + ] + } + } + } + } + ] + } + ] + }, + { + "$id": "1343", + "name": "checkLabels", + "resourceName": "AzureAppConfiguration", + "summary": "Requests the headers and status of the given resource.", + "doc": "Requests the headers and status of the given resource.", + "accessibility": "public", + "parameters": [ + { + "$id": "1344", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1345", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1346", + "type": { + "$id": "1347", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1348", + "name": "name", + "nameInRequest": "name", + "doc": "A filter for the name of the returned labels.", + "type": { + "$id": "1349", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1350", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1351", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1352", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "1353", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1354", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "1355", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1356", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "1357", + "kind": "array", + "name": "ArrayLabelFields", + "valueType": { + "$ref": "128" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1358", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1359", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1360", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1361", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1362", + "kind": "constant", + "valueType": { + "$id": "1363", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1364", + "statusCodes": [ + 200 + ], + "headers": [ + { + "$id": "1365", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1366", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "HEAD", + "uri": "{endpoint}", + "path": "/labels", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.checkLabels", + "decorators": [], + "examples": [ + { + "$id": "1367", + "kind": "http", + "name": "Requests the headers and status of the given resource.", + "description": "Requests the headers and status of the given resource.", + "filePath": "2024-09-01/CheckLabels.json", + "parameters": [ + { + "$id": "1368", + "parameter": { + "$ref": "1344" + }, + "value": { + "$id": "1369", + "kind": "string", + "type": { + "$ref": "1345" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "1370", + "response": { + "$ref": "1364" + }, + "statusCode": 200 + } + ] + } + ] + }, + { + "$id": "1371", + "name": "putLock", + "resourceName": "AzureAppConfiguration", + "summary": "Locks a key-value.", + "doc": "Locks a key-value.", + "accessibility": "public", + "parameters": [ + { + "$id": "1372", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1373", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1374", + "type": { + "$id": "1375", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1376", + "name": "key", + "nameInRequest": "key", + "doc": "The key of the key-value to lock.", + "type": { + "$id": "1377", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1378", + "name": "label", + "nameInRequest": "label", + "doc": "The label, if any, of the key-value to lock.", + "type": { + "$id": "1379", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1380", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1381", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1382", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "1383", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1384", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "1385", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1386", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1387", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1388", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1389", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1390", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1391", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "182" + }, + "headers": [ + { + "$id": "1392", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1393", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1394", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "1395", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1396", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "32" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.kv+json", + "application/problem+json" + ] + } + ], + "httpMethod": "PUT", + "uri": "{endpoint}", + "path": "/locks/{key}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.putLock", + "decorators": [], + "examples": [ + { + "$id": "1397", + "kind": "http", + "name": "Locks a key-value.", + "description": "Locks a key-value.", + "filePath": "2024-09-01/PutLock.json", + "parameters": [ + { + "$id": "1398", + "parameter": { + "$ref": "1372" + }, + "value": { + "$id": "1399", + "kind": "string", + "type": { + "$ref": "1373" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1400", + "parameter": { + "$ref": "1376" + }, + "value": { + "$id": "1401", + "kind": "string", + "type": { + "$ref": "1377" + }, + "value": "Message" + } + } + ], + "responses": [ + { + "$id": "1402", + "response": { + "$ref": "1391" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1403", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "1404", + "etag": { + "$id": "1405", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV4" + }, + "key": { + "$id": "1406", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "1407", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "1408", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "1409" + } + }, + "locked": { + "$id": "1410", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": true + }, + "last_modified": { + "$id": "1411", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + }, + { + "$id": "1412", + "kind": "http", + "name": "Locks a key-value using If-Match header.", + "description": "Locks a key-value using If-Match header.", + "filePath": "2024-09-01/PutLock_IfMatch.json", + "parameters": [ + { + "$id": "1413", + "parameter": { + "$ref": "1372" + }, + "value": { + "$id": "1414", + "kind": "string", + "type": { + "$ref": "1373" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1415", + "parameter": { + "$ref": "1376" + }, + "value": { + "$id": "1416", + "kind": "string", + "type": { + "$ref": "1377" + }, + "value": "Message" + } + }, + { + "$id": "1417", + "parameter": { + "$ref": "1382" + }, + "value": { + "$id": "1418", + "kind": "string", + "type": { + "$ref": "1383" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "1419", + "response": { + "$ref": "1391" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1420", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "1421", + "etag": { + "$id": "1422", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + }, + "key": { + "$id": "1423", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "1424", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "1425", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "1426" + } + }, + "locked": { + "$id": "1427", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": true + }, + "last_modified": { + "$id": "1428", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + } + ] + }, + { + "$id": "1429", + "name": "deleteLock", + "resourceName": "AzureAppConfiguration", + "summary": "Unlocks a key-value.", + "doc": "Unlocks a key-value.", + "accessibility": "public", + "parameters": [ + { + "$id": "1430", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1431", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1432", + "type": { + "$id": "1433", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1434", + "name": "key", + "nameInRequest": "key", + "doc": "The key of the key-value to unlock.", + "type": { + "$id": "1435", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Path", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1436", + "name": "label", + "nameInRequest": "label", + "doc": "The label, if any, of the key-value to unlock.", + "type": { + "$id": "1437", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1438", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1439", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1440", + "name": "ifMatch", + "nameInRequest": "If-Match", + "doc": "Used to perform an operation only if the targeted resource's etag matches the\nvalue provided.", + "type": { + "$id": "1441", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1442", + "name": "ifNoneMatch", + "nameInRequest": "If-None-Match", + "doc": "Used to perform an operation only if the targeted resource's etag does not\nmatch the value provided.", + "type": { + "$id": "1443", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1444", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1445", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1446", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1447", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1448", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1449", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "182" + }, + "headers": [ + { + "$id": "1450", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1451", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1452", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "1453", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1454", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "32" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.kv+json", + "application/problem+json" + ] + } + ], + "httpMethod": "DELETE", + "uri": "{endpoint}", + "path": "/locks/{key}", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.deleteLock", + "decorators": [], + "examples": [ + { + "$id": "1455", + "kind": "http", + "name": "Unlocks a key-value.", + "description": "Unlocks a key-value.", + "filePath": "2024-09-01/DeleteLock.json", + "parameters": [ + { + "$id": "1456", + "parameter": { + "$ref": "1430" + }, + "value": { + "$id": "1457", + "kind": "string", + "type": { + "$ref": "1431" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1458", + "parameter": { + "$ref": "1434" + }, + "value": { + "$id": "1459", + "kind": "string", + "type": { + "$ref": "1435" + }, + "value": "Message" + } + } + ], + "responses": [ + { + "$id": "1460", + "response": { + "$ref": "1449" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1461", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "1462", + "etag": { + "$id": "1463", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "0BGYCoQ6iNdp5NtQ7N8shrobo6s" + }, + "key": { + "$id": "1464", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "1465", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "1466", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "1467" + } + }, + "locked": { + "$id": "1468", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "1469", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + }, + { + "$id": "1470", + "kind": "http", + "name": "Unlocks a key-value using If-Match header.", + "description": "Unlocks a key-value using If-Match header.", + "filePath": "2024-09-01/DeleteLock_IfMatch.json", + "parameters": [ + { + "$id": "1471", + "parameter": { + "$ref": "1430" + }, + "value": { + "$id": "1472", + "kind": "string", + "type": { + "$ref": "1431" + }, + "value": "2024-09-01" + } + }, + { + "$id": "1473", + "parameter": { + "$ref": "1434" + }, + "value": { + "$id": "1474", + "kind": "string", + "type": { + "$ref": "1435" + }, + "value": "Message" + } + }, + { + "$id": "1475", + "parameter": { + "$ref": "1440" + }, + "value": { + "$id": "1476", + "kind": "string", + "type": { + "$ref": "1441" + }, + "value": "\"L10qpBghN693OaxydgTkLmrBbV5\"" + } + } + ], + "responses": [ + { + "$id": "1477", + "response": { + "$ref": "1449" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1478", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "1479", + "etag": { + "$id": "1480", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV5" + }, + "key": { + "$id": "1481", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "1482", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "1483", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "1484" + } + }, + "locked": { + "$id": "1485", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "1486", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + } + } + ] + } + ] + }, + { + "$id": "1487", + "name": "getRevisions", + "resourceName": "AzureAppConfiguration", + "summary": "Gets a list of key-value revisions.", + "doc": "Gets a list of key-value revisions.", + "accessibility": "public", + "parameters": [ + { + "$id": "1488", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1489", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1490", + "type": { + "$id": "1491", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1492", + "name": "key", + "nameInRequest": "key", + "doc": "A filter used to match keys. Syntax reference:\nhttps://aka.ms/azconfig/docs/restapirevisions", + "type": { + "$id": "1493", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1494", + "name": "label", + "nameInRequest": "label", + "doc": "A filter used to match labels. Syntax reference:\nhttps://aka.ms/azconfig/docs/restapirevisions", + "type": { + "$id": "1495", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1496", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1497", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1498", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "1499", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1500", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "1501", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1502", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "1503", + "kind": "array", + "name": "ArrayKeyValueFields", + "valueType": { + "$ref": "8" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1504", + "name": "tags", + "nameInRequest": "tags", + "doc": "A filter used to query by tags. Syntax reference:\nhttps://aka.ms/azconfig/docs/restapirevisions", + "type": { + "$id": "1505", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "1506", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": true, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1507", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1508", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1509", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1510", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1511", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1512", + "statusCodes": [ + 200 + ], + "bodyType": { + "$ref": "179" + }, + "headers": [ + { + "$id": "1513", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1514", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1515", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "1516", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1517", + "name": "contentType", + "nameInResponse": "Content-Type", + "doc": "Content-Type header", + "type": { + "$ref": "26" + } + } + ], + "isErrorResponse": false, + "contentTypes": [ + "application/vnd.microsoft.appconfig.kvset+json", + "application/problem+json" + ] + } + ], + "httpMethod": "GET", + "uri": "{endpoint}", + "path": "/revisions", + "bufferResponse": true, + "paging": { + "$id": "1518", + "itemPropertySegments": [ + "items" + ], + "nextLink": { + "$id": "1519", + "responseSegments": [ + "@nextLink" + ], + "responseLocation": "Body" + } + }, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.getRevisions", + "decorators": [], + "examples": [ + { + "$id": "1520", + "kind": "http", + "name": "Gets a list of key-value revisions.", + "description": "Gets a list of key-value revisions.", + "filePath": "2024-09-01/GetRevisions.json", + "parameters": [ + { + "$id": "1521", + "parameter": { + "$ref": "1488" + }, + "value": { + "$id": "1522", + "kind": "string", + "type": { + "$ref": "1489" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "1523", + "response": { + "$ref": "1512" + }, + "statusCode": 200, + "bodyValue": { + "$id": "1524", + "kind": "model", + "type": { + "$ref": "179" + }, + "value": { + "$id": "1525", + "items": { + "$id": "1526", + "kind": "array", + "type": { + "$ref": "181" + }, + "value": [ + { + "$id": "1527", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "1528", + "etag": { + "$id": "1529", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "0BGYCoQ6iNdp5NtQ7N8shrobo6s" + }, + "key": { + "$id": "1530", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "1531", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "1532", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "1533" + } + }, + "locked": { + "$id": "1534", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "1535", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:32+00:00" + } + } + }, + { + "$id": "1536", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "1537", + "etag": { + "$id": "1538", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "L10qpBghN693OaxydgTkLmrBbV4" + }, + "key": { + "$id": "1539", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "1540", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "A new message." + }, + "tags": { + "$id": "1541", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "1542" + } + }, + "locked": { + "$id": "1543", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "1544", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:52:20+00:00" + } + } + }, + { + "$id": "1545", + "kind": "model", + "type": { + "$ref": "182" + }, + "value": { + "$id": "1546", + "etag": { + "$id": "1547", + "kind": "string", + "type": { + "$ref": "215" + }, + "value": "tnIHBkDYQwtdNMLoWtr5aybkKwL" + }, + "key": { + "$id": "1548", + "kind": "string", + "type": { + "$ref": "184" + }, + "value": "Message" + }, + "value": { + "$id": "1549", + "kind": "string", + "type": { + "$ref": "196" + }, + "value": "Hello World!" + }, + "tags": { + "$id": "1550", + "kind": "dict", + "type": { + "$ref": "205" + }, + "value": { + "$id": "1551" + } + }, + "locked": { + "$id": "1552", + "kind": "boolean", + "type": { + "$ref": "211" + }, + "value": false + }, + "last_modified": { + "$id": "1553", + "kind": "string", + "type": { + "$ref": "200" + }, + "value": "2019-08-27T16:50:47+00:00" + } + } + } + ] + } + } + } + } + ] + } + ] + }, + { + "$id": "1554", + "name": "checkRevisions", + "resourceName": "AzureAppConfiguration", + "summary": "Requests the headers and status of the given resource.", + "doc": "Requests the headers and status of the given resource.", + "accessibility": "public", + "parameters": [ + { + "$id": "1555", + "name": "apiVersion", + "nameInRequest": "api-version", + "doc": "The API version to use for this operation.", + "type": { + "$id": "1556", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": true, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Client", + "defaultValue": { + "$id": "1557", + "type": { + "$id": "1558", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string" + }, + "value": "2024-09-01" + }, + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1559", + "name": "key", + "nameInRequest": "key", + "doc": "A filter used to match keys. Syntax reference:\nhttps://aka.ms/azconfig/docs/restapirevisions", + "type": { + "$id": "1560", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1561", + "name": "label", + "nameInRequest": "label", + "doc": "A filter used to match labels. Syntax reference:\nhttps://aka.ms/azconfig/docs/restapirevisions", + "type": { + "$id": "1562", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1563", + "name": "syncToken", + "nameInRequest": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1564", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1565", + "name": "after", + "nameInRequest": "After", + "doc": "Instructs the server to return elements that appear after the element referred\nto by the specified token.", + "type": { + "$id": "1566", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1567", + "name": "acceptDatetime", + "nameInRequest": "Accept-Datetime", + "doc": "Requests the server to respond with the state of the resource at the specified\ntime.", + "type": { + "$id": "1568", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1569", + "name": "select", + "nameInRequest": "$Select", + "doc": "Used to select what fields are present in the returned resource(s).", + "type": { + "$id": "1570", + "kind": "array", + "name": "ArrayKeyValueFields", + "valueType": { + "$ref": "8" + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "arraySerializationDelimiter": ",", + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1571", + "name": "tags", + "nameInRequest": "tags", + "doc": "A filter used to query by tags. Syntax reference:\nhttps://aka.ms/azconfig/docs/restapirevisions", + "type": { + "$id": "1572", + "kind": "array", + "name": "Array", + "valueType": { + "$id": "1573", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "crossLanguageDefinitionId": "TypeSpec.Array", + "decorators": [] + }, + "location": "Query", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": true, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1574", + "name": "clientRequestId", + "nameInRequest": "x-ms-client-request-id", + "doc": "An opaque, globally-unique, client-generated string identifier for the request.", + "type": { + "$id": "1575", + "kind": "string", + "name": "uuid", + "crossLanguageDefinitionId": "Azure.Core.uuid", + "baseType": { + "$id": "1576", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": false, + "kind": "Method", + "decorators": [], + "skipUrlEncoding": false + }, + { + "$id": "1577", + "name": "accept", + "nameInRequest": "Accept", + "type": { + "$id": "1578", + "kind": "constant", + "valueType": { + "$id": "1579", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + }, + "value": "application/json", + "decorators": [] + }, + "location": "Header", + "isApiVersion": false, + "isContentType": false, + "isEndpoint": false, + "explode": false, + "isRequired": true, + "kind": "Constant", + "decorators": [], + "skipUrlEncoding": false + } + ], + "responses": [ + { + "$id": "1580", + "statusCodes": [ + 200 + ], + "headers": [ + { + "$id": "1581", + "name": "syncToken", + "nameInResponse": "Sync-Token", + "doc": "Used to guarantee real-time consistency between requests.", + "type": { + "$id": "1582", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + }, + { + "$id": "1583", + "name": "etagHeader", + "nameInResponse": "ETag", + "doc": "A value representing the current state of the resource.", + "type": { + "$id": "1584", + "kind": "string", + "name": "string", + "crossLanguageDefinitionId": "TypeSpec.string", + "decorators": [] + } + } + ], + "isErrorResponse": false + } + ], + "httpMethod": "HEAD", + "uri": "{endpoint}", + "path": "/revisions", + "bufferResponse": true, + "generateProtocolMethod": true, + "generateConvenienceMethod": true, + "crossLanguageDefinitionId": "AzureAppConfiguration.checkRevisions", + "decorators": [], + "examples": [ + { + "$id": "1585", + "kind": "http", + "name": "Requests the headers and status of the given resource.", + "description": "Requests the headers and status of the given resource.", + "filePath": "2024-09-01/CheckRevisions.json", + "parameters": [ + { + "$id": "1586", + "parameter": { + "$ref": "1555" + }, + "value": { + "$id": "1587", + "kind": "string", + "type": { + "$ref": "1556" + }, + "value": "2024-09-01" + } + } + ], + "responses": [ + { + "$id": "1588", + "response": { + "$ref": "1580" + }, + "statusCode": 200 + } + ] + } + ] + } + ], + "parameters": [ + { + "$id": "1589", + "name": "endpoint", + "nameInRequest": "endpoint", + "type": { + "$id": "1590", + "kind": "url", + "name": "url", + "crossLanguageDefinitionId": "TypeSpec.url" + }, + "location": "Uri", + "isApiVersion": false, + "isContentType": false, + "isRequired": true, + "isEndpoint": true, + "skipUrlEncoding": false, + "explode": false, + "kind": "Client" + } + ], + "decorators": [ + { + "$id": "1591", + "name": "TypeSpec.@service", + "arguments": { + "$id": "1592", + "options": { + "$id": "1593", + "title": "Azure App Configuration" + } + } + } + ], + "crossLanguageDefinitionId": "AzureAppConfiguration", + "apiVersions": [ + "2023-11-01", + "2024-09-01" + ] + } + ], + "auth": { + "$id": "1594", + "apiKey": { + "$id": "1595", + "name": "Connection String", + "in": "header" + }, + "oAuth2": { + "$id": "1596", + "scopes": [ + "https://azconfig.io/.default" + ] + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/LiveMetrics.sln b/sdk/applicationinsights/LiveMetrics/LiveMetrics.sln new file mode 100644 index 000000000000..202d00182aa1 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/LiveMetrics.sln @@ -0,0 +1,50 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiveMetrics", "src\LiveMetrics.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiveMetrics.Tests", "tests\LiveMetrics.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/AggregationType.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/AggregationType.cs new file mode 100644 index 000000000000..f785f0dec7ee --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/AggregationType.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Aggregation type. + public readonly partial struct AggregationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AggregationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AvgValue = "Avg"; + private const string SumValue = "Sum"; + private const string MinValue = "Min"; + private const string MaxValue = "Max"; + + /// Average. + public static AggregationType Avg { get; } = new AggregationType(AvgValue); + /// Sum. + public static AggregationType Sum { get; } = new AggregationType(SumValue); + /// Minimum. + public static AggregationType Min { get; } = new AggregationType(MinValue); + /// Maximum. + public static AggregationType Max { get; } = new AggregationType(MaxValue); + /// Determines if two values are the same. + public static bool operator ==(AggregationType left, AggregationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AggregationType left, AggregationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AggregationType(string value) => new AggregationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AggregationType other && Equals(other); + /// + public bool Equals(AggregationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.Serialization.cs new file mode 100644 index 000000000000..981f6569019f --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.Serialization.cs @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class CollectionConfigurationError : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("CollectionConfigurationErrorType"u8); + writer.WriteStringValue(CollectionConfigurationErrorType.ToString()); + writer.WritePropertyName("Message"u8); + writer.WriteStringValue(Message); + writer.WritePropertyName("FullException"u8); + writer.WriteStringValue(FullException); + writer.WritePropertyName("Data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CollectionConfigurationError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCollectionConfigurationError(document.RootElement, options); + } + + internal static CollectionConfigurationError DeserializeCollectionConfigurationError(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CollectionConfigurationErrorType collectionConfigurationErrorType = default; + string message = default; + string fullException = default; + IList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("CollectionConfigurationErrorType"u8)) + { + collectionConfigurationErrorType = new CollectionConfigurationErrorType(property.Value.GetString()); + continue; + } + if (property.NameEquals("Message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("FullException"u8)) + { + fullException = property.Value.GetString(); + continue; + } + if (property.NameEquals("Data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CollectionConfigurationError(collectionConfigurationErrorType, message, fullException, data, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support writing '{options.Format}' format."); + } + } + + CollectionConfigurationError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCollectionConfigurationError(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CollectionConfigurationError)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CollectionConfigurationError FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCollectionConfigurationError(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.cs new file mode 100644 index 000000000000..2c827786fc4b --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationError.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Represents an error while SDK parses and applies an instance of CollectionConfigurationInfo. + public partial class CollectionConfigurationError + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Error type. + /// Error message. + /// Exception that led to the creation of the configuration error. + /// Custom properties to add more information to the error. + /// , or is null. + public CollectionConfigurationError(CollectionConfigurationErrorType collectionConfigurationErrorType, string message, string fullException, IEnumerable data) + { + Argument.AssertNotNull(message, nameof(message)); + Argument.AssertNotNull(fullException, nameof(fullException)); + Argument.AssertNotNull(data, nameof(data)); + + CollectionConfigurationErrorType = collectionConfigurationErrorType; + Message = message; + FullException = fullException; + Data = data.ToList(); + } + + /// Initializes a new instance of . + /// Error type. + /// Error message. + /// Exception that led to the creation of the configuration error. + /// Custom properties to add more information to the error. + /// Keeps track of any properties unknown to the library. + internal CollectionConfigurationError(CollectionConfigurationErrorType collectionConfigurationErrorType, string message, string fullException, IList data, IDictionary serializedAdditionalRawData) + { + CollectionConfigurationErrorType = collectionConfigurationErrorType; + Message = message; + FullException = fullException; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CollectionConfigurationError() + { + } + + /// Error type. + public CollectionConfigurationErrorType CollectionConfigurationErrorType { get; } + /// Error message. + public string Message { get; } + /// Exception that led to the creation of the configuration error. + public string FullException { get; } + /// Custom properties to add more information to the error. + public IList Data { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationErrorType.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationErrorType.cs new file mode 100644 index 000000000000..9e116938866b --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationErrorType.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Collection configuration error type reported by the client SDK. + public readonly partial struct CollectionConfigurationErrorType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CollectionConfigurationErrorType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UnknownValue = "Unknown"; + private const string PerformanceCounterParsingValue = "PerformanceCounterParsing"; + private const string PerformanceCounterUnexpectedValue = "PerformanceCounterUnexpected"; + private const string PerformanceCounterDuplicateIdsValue = "PerformanceCounterDuplicateIds"; + private const string DocumentStreamDuplicateIdsValue = "DocumentStreamDuplicateIds"; + private const string DocumentStreamFailureToCreateValue = "DocumentStreamFailureToCreate"; + private const string DocumentStreamFailureToCreateFilterUnexpectedValue = "DocumentStreamFailureToCreateFilterUnexpected"; + private const string MetricDuplicateIdsValue = "MetricDuplicateIds"; + private const string MetricTelemetryTypeUnsupportedValue = "MetricTelemetryTypeUnsupported"; + private const string MetricFailureToCreateValue = "MetricFailureToCreate"; + private const string MetricFailureToCreateFilterUnexpectedValue = "MetricFailureToCreateFilterUnexpected"; + private const string FilterFailureToCreateUnexpectedValue = "FilterFailureToCreateUnexpected"; + private const string CollectionConfigurationFailureToCreateUnexpectedValue = "CollectionConfigurationFailureToCreateUnexpected"; + + /// Unknown error type. + public static CollectionConfigurationErrorType Unknown { get; } = new CollectionConfigurationErrorType(UnknownValue); + /// Performance counter parsing error. + public static CollectionConfigurationErrorType PerformanceCounterParsing { get; } = new CollectionConfigurationErrorType(PerformanceCounterParsingValue); + /// Performance counter unexpected error. + public static CollectionConfigurationErrorType PerformanceCounterUnexpected { get; } = new CollectionConfigurationErrorType(PerformanceCounterUnexpectedValue); + /// Performance counter duplicate ids. + public static CollectionConfigurationErrorType PerformanceCounterDuplicateIds { get; } = new CollectionConfigurationErrorType(PerformanceCounterDuplicateIdsValue); + /// Document stream duplication ids. + public static CollectionConfigurationErrorType DocumentStreamDuplicateIds { get; } = new CollectionConfigurationErrorType(DocumentStreamDuplicateIdsValue); + /// Document stream failed to create. + public static CollectionConfigurationErrorType DocumentStreamFailureToCreate { get; } = new CollectionConfigurationErrorType(DocumentStreamFailureToCreateValue); + /// Document stream failed to create filter unexpectedly. + public static CollectionConfigurationErrorType DocumentStreamFailureToCreateFilterUnexpected { get; } = new CollectionConfigurationErrorType(DocumentStreamFailureToCreateFilterUnexpectedValue); + /// Metric duplicate ids. + public static CollectionConfigurationErrorType MetricDuplicateIds { get; } = new CollectionConfigurationErrorType(MetricDuplicateIdsValue); + /// Metric telemetry type unsupported. + public static CollectionConfigurationErrorType MetricTelemetryTypeUnsupported { get; } = new CollectionConfigurationErrorType(MetricTelemetryTypeUnsupportedValue); + /// Metric failed to create. + public static CollectionConfigurationErrorType MetricFailureToCreate { get; } = new CollectionConfigurationErrorType(MetricFailureToCreateValue); + /// Metric failed to create filter unexpectedly. + public static CollectionConfigurationErrorType MetricFailureToCreateFilterUnexpected { get; } = new CollectionConfigurationErrorType(MetricFailureToCreateFilterUnexpectedValue); + /// Filter failed to create unexpectedly. + public static CollectionConfigurationErrorType FilterFailureToCreateUnexpected { get; } = new CollectionConfigurationErrorType(FilterFailureToCreateUnexpectedValue); + /// Collection configuration failed to create unexpectedly. + public static CollectionConfigurationErrorType CollectionConfigurationFailureToCreateUnexpected { get; } = new CollectionConfigurationErrorType(CollectionConfigurationFailureToCreateUnexpectedValue); + /// Determines if two values are the same. + public static bool operator ==(CollectionConfigurationErrorType left, CollectionConfigurationErrorType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CollectionConfigurationErrorType left, CollectionConfigurationErrorType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CollectionConfigurationErrorType(string value) => new CollectionConfigurationErrorType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CollectionConfigurationErrorType other && Equals(other); + /// + public bool Equals(CollectionConfigurationErrorType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.Serialization.cs new file mode 100644 index 000000000000..a2cccb1e0ee5 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.Serialization.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class CollectionConfigurationInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("ETag"u8); + writer.WriteStringValue(ETag); + writer.WritePropertyName("Metrics"u8); + writer.WriteStartArray(); + foreach (var item in Metrics) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("DocumentStreams"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreams) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsDefined(QuotaInfo)) + { + writer.WritePropertyName("QuotaInfo"u8); + writer.WriteObjectValue(QuotaInfo, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CollectionConfigurationInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCollectionConfigurationInfo(document.RootElement, options); + } + + internal static CollectionConfigurationInfo DeserializeCollectionConfigurationInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string eTag = default; + IReadOnlyList metrics = default; + IReadOnlyList documentStreams = default; + QuotaConfigurationInfo quotaInfo = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ETag"u8)) + { + eTag = property.Value.GetString(); + continue; + } + if (property.NameEquals("Metrics"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DerivedMetricInfo.DeserializeDerivedMetricInfo(item, options)); + } + metrics = array; + continue; + } + if (property.NameEquals("DocumentStreams"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DocumentStreamInfo.DeserializeDocumentStreamInfo(item, options)); + } + documentStreams = array; + continue; + } + if (property.NameEquals("QuotaInfo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + quotaInfo = QuotaConfigurationInfo.DeserializeQuotaConfigurationInfo(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CollectionConfigurationInfo(eTag, metrics, documentStreams, quotaInfo, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support writing '{options.Format}' format."); + } + } + + CollectionConfigurationInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCollectionConfigurationInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CollectionConfigurationInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CollectionConfigurationInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCollectionConfigurationInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.cs new file mode 100644 index 000000000000..2202b8fcc18b --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/CollectionConfigurationInfo.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Represents the collection configuration - a customizable description of performance counters, metrics, and full telemetry documents to be collected by the client SDK. + public partial class CollectionConfigurationInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// An encoded string that indicates whether the collection configuration is changed. + /// An array of metric configuration info. + /// An array of document stream configuration info. + /// , or is null. + internal CollectionConfigurationInfo(string eTag, IEnumerable metrics, IEnumerable documentStreams) + { + Argument.AssertNotNull(eTag, nameof(eTag)); + Argument.AssertNotNull(metrics, nameof(metrics)); + Argument.AssertNotNull(documentStreams, nameof(documentStreams)); + + ETag = eTag; + Metrics = metrics.ToList(); + DocumentStreams = documentStreams.ToList(); + } + + /// Initializes a new instance of . + /// An encoded string that indicates whether the collection configuration is changed. + /// An array of metric configuration info. + /// An array of document stream configuration info. + /// Controls document quotas to be sent to Live Metrics. + /// Keeps track of any properties unknown to the library. + internal CollectionConfigurationInfo(string eTag, IReadOnlyList metrics, IReadOnlyList documentStreams, QuotaConfigurationInfo quotaInfo, IDictionary serializedAdditionalRawData) + { + ETag = eTag; + Metrics = metrics; + DocumentStreams = documentStreams; + QuotaInfo = quotaInfo; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CollectionConfigurationInfo() + { + } + + /// An encoded string that indicates whether the collection configuration is changed. + public string ETag { get; } + /// An array of metric configuration info. + public IReadOnlyList Metrics { get; } + /// An array of document stream configuration info. + public IReadOnlyList DocumentStreams { get; } + /// Controls document quotas to be sent to Live Metrics. + public QuotaConfigurationInfo QuotaInfo { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.Serialization.cs new file mode 100644 index 000000000000..33f866d682b4 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.Serialization.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class DerivedMetricInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("Id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("TelemetryType"u8); + writer.WriteStringValue(TelemetryType); + writer.WritePropertyName("FilterGroups"u8); + writer.WriteStartArray(); + foreach (var item in FilterGroups) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("Projection"u8); + writer.WriteStringValue(Projection); + writer.WritePropertyName("Aggregation"u8); + writer.WriteStringValue(Aggregation.ToString()); + writer.WritePropertyName("BackEndAggregation"u8); + writer.WriteStringValue(BackEndAggregation.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DerivedMetricInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDerivedMetricInfo(document.RootElement, options); + } + + internal static DerivedMetricInfo DeserializeDerivedMetricInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + string telemetryType = default; + IReadOnlyList filterGroups = default; + string projection = default; + AggregationType aggregation = default; + AggregationType backEndAggregation = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("TelemetryType"u8)) + { + telemetryType = property.Value.GetString(); + continue; + } + if (property.NameEquals("FilterGroups"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FilterConjunctionGroupInfo.DeserializeFilterConjunctionGroupInfo(item, options)); + } + filterGroups = array; + continue; + } + if (property.NameEquals("Projection"u8)) + { + projection = property.Value.GetString(); + continue; + } + if (property.NameEquals("Aggregation"u8)) + { + aggregation = new AggregationType(property.Value.GetString()); + continue; + } + if (property.NameEquals("BackEndAggregation"u8)) + { + backEndAggregation = new AggregationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DerivedMetricInfo( + id, + telemetryType, + filterGroups, + projection, + aggregation, + backEndAggregation, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support writing '{options.Format}' format."); + } + } + + DerivedMetricInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDerivedMetricInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DerivedMetricInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DerivedMetricInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDerivedMetricInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.cs new file mode 100644 index 000000000000..bf65e8969c59 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DerivedMetricInfo.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// A metric configuration set by UX to scope the metrics it's interested in. + public partial class DerivedMetricInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// metric configuration identifier. + /// Telemetry type. + /// A collection of filters to scope metrics that UX needs. + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + /// Aggregation type. This is the aggregation done from everything within a single server. + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + /// , , or is null. + internal DerivedMetricInfo(string id, string telemetryType, IEnumerable filterGroups, string projection, AggregationType aggregation, AggregationType backEndAggregation) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(telemetryType, nameof(telemetryType)); + Argument.AssertNotNull(filterGroups, nameof(filterGroups)); + Argument.AssertNotNull(projection, nameof(projection)); + + Id = id; + TelemetryType = telemetryType; + FilterGroups = filterGroups.ToList(); + Projection = projection; + Aggregation = aggregation; + BackEndAggregation = backEndAggregation; + } + + /// Initializes a new instance of . + /// metric configuration identifier. + /// Telemetry type. + /// A collection of filters to scope metrics that UX needs. + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + /// Aggregation type. This is the aggregation done from everything within a single server. + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + /// Keeps track of any properties unknown to the library. + internal DerivedMetricInfo(string id, string telemetryType, IReadOnlyList filterGroups, string projection, AggregationType aggregation, AggregationType backEndAggregation, IDictionary serializedAdditionalRawData) + { + Id = id; + TelemetryType = telemetryType; + FilterGroups = filterGroups; + Projection = projection; + Aggregation = aggregation; + BackEndAggregation = backEndAggregation; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DerivedMetricInfo() + { + } + + /// metric configuration identifier. + public string Id { get; } + /// Telemetry type. + public string TelemetryType { get; } + /// A collection of filters to scope metrics that UX needs. + public IReadOnlyList FilterGroups { get; } + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + public string Projection { get; } + /// Aggregation type. This is the aggregation done from everything within a single server. + public AggregationType Aggregation { get; } + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + public AggregationType BackEndAggregation { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Docs/LiveMetricsClient.xml b/sdk/applicationinsights/LiveMetrics/src/Generated/Docs/LiveMetricsClient.xml new file mode 100644 index 000000000000..d20fe9db0cf7 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Docs/LiveMetricsClient.xml @@ -0,0 +1,439 @@ + + + + + +This sample shows how to call IsSubscribedAsync. + response = await client.IsSubscribedAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call IsSubscribed. + response = client.IsSubscribed("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call IsSubscribedAsync and parse the result. + + + + +This sample shows how to call IsSubscribed and parse the result. + + + + +This sample shows how to call PublishAsync. + response = await client.PublishAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call Publish. + response = client.Publish("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); +]]> + + + +This sample shows how to call PublishAsync and parse the result. + + + + +This sample shows how to call Publish and parse the result. + + + + \ No newline at end of file diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.Serialization.cs new file mode 100644 index 000000000000..8dba2b0d193c --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class DocumentFilterConjunctionGroupInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("TelemetryType"u8); + writer.WriteStringValue(TelemetryType.ToString()); + writer.WritePropertyName("Filters"u8); + writer.WriteObjectValue(Filters, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DocumentFilterConjunctionGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentFilterConjunctionGroupInfo(document.RootElement, options); + } + + internal static DocumentFilterConjunctionGroupInfo DeserializeDocumentFilterConjunctionGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + TelemetryType telemetryType = default; + FilterConjunctionGroupInfo filters = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("TelemetryType"u8)) + { + telemetryType = new TelemetryType(property.Value.GetString()); + continue; + } + if (property.NameEquals("Filters"u8)) + { + filters = FilterConjunctionGroupInfo.DeserializeFilterConjunctionGroupInfo(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DocumentFilterConjunctionGroupInfo(telemetryType, filters, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support writing '{options.Format}' format."); + } + } + + DocumentFilterConjunctionGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDocumentFilterConjunctionGroupInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentFilterConjunctionGroupInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DocumentFilterConjunctionGroupInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDocumentFilterConjunctionGroupInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.cs new file mode 100644 index 000000000000..ab47aa5a5a85 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentFilterConjunctionGroupInfo.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// A collection of filters for a specific telemetry type. + public partial class DocumentFilterConjunctionGroupInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Telemetry type. + /// An array of filter groups. + /// is null. + internal DocumentFilterConjunctionGroupInfo(TelemetryType telemetryType, FilterConjunctionGroupInfo filters) + { + Argument.AssertNotNull(filters, nameof(filters)); + + TelemetryType = telemetryType; + Filters = filters; + } + + /// Initializes a new instance of . + /// Telemetry type. + /// An array of filter groups. + /// Keeps track of any properties unknown to the library. + internal DocumentFilterConjunctionGroupInfo(TelemetryType telemetryType, FilterConjunctionGroupInfo filters, IDictionary serializedAdditionalRawData) + { + TelemetryType = telemetryType; + Filters = filters; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DocumentFilterConjunctionGroupInfo() + { + } + + /// Telemetry type. + public TelemetryType TelemetryType { get; } + /// An array of filter groups. + public FilterConjunctionGroupInfo Filters { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.Serialization.cs new file mode 100644 index 000000000000..2735f6e690c3 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + [PersistableModelProxy(typeof(UnknownDocumentIngress))] + public partial class DocumentIngress : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("DocumentType"u8); + writer.WriteStringValue(DocumentType.ToString()); + if (Optional.IsCollectionDefined(DocumentStreamIds)) + { + writer.WritePropertyName("DocumentStreamIds"u8); + writer.WriteStartArray(); + foreach (var item in DocumentStreamIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Properties)) + { + writer.WritePropertyName("Properties"u8); + writer.WriteStartArray(); + foreach (var item in Properties) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DocumentIngress IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentIngress(document.RootElement, options); + } + + internal static DocumentIngress DeserializeDocumentIngress(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("DocumentType", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "Event": return Event.DeserializeEvent(element, options); + case "Exception": return Exception.DeserializeException(element, options); + case "RemoteDependency": return RemoteDependency.DeserializeRemoteDependency(element, options); + case "Request": return Request.DeserializeRequest(element, options); + case "Trace": return Trace.DeserializeTrace(element, options); + } + } + return UnknownDocumentIngress.DeserializeUnknownDocumentIngress(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{options.Format}' format."); + } + } + + DocumentIngress IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDocumentIngress(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DocumentIngress FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDocumentIngress(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.cs new file mode 100644 index 000000000000..495a1ba03e02 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentIngress.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// + /// Base class of the specific document types. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public abstract partial class DocumentIngress + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected DocumentIngress() + { + DocumentStreamIds = new ChangeTrackingList(); + Properties = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + internal DocumentIngress(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData) + { + DocumentType = documentType; + DocumentStreamIds = documentStreamIds; + Properties = properties; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + internal DocumentType DocumentType { get; set; } + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + public IList DocumentStreamIds { get; } + /// Collection of custom properties. + public IList Properties { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.Serialization.cs new file mode 100644 index 000000000000..690d5fca8a33 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.Serialization.cs @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class DocumentStreamInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("Id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("DocumentFilterGroups"u8); + writer.WriteStartArray(); + foreach (var item in DocumentFilterGroups) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DocumentStreamInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentStreamInfo(document.RootElement, options); + } + + internal static DocumentStreamInfo DeserializeDocumentStreamInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + IReadOnlyList documentFilterGroups = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentFilterGroups"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DocumentFilterConjunctionGroupInfo.DeserializeDocumentFilterConjunctionGroupInfo(item, options)); + } + documentFilterGroups = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DocumentStreamInfo(id, documentFilterGroups, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support writing '{options.Format}' format."); + } + } + + DocumentStreamInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDocumentStreamInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentStreamInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DocumentStreamInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDocumentStreamInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.cs new file mode 100644 index 000000000000..02101af6454e --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentStreamInfo.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Configurations/filters set by UX to scope the document/telemetry it's interested in. + public partial class DocumentStreamInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Identifier of the document stream initiated by a UX. + /// Gets or sets an OR-connected collection of filter groups. + /// or is null. + internal DocumentStreamInfo(string id, IEnumerable documentFilterGroups) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(documentFilterGroups, nameof(documentFilterGroups)); + + Id = id; + DocumentFilterGroups = documentFilterGroups.ToList(); + } + + /// Initializes a new instance of . + /// Identifier of the document stream initiated by a UX. + /// Gets or sets an OR-connected collection of filter groups. + /// Keeps track of any properties unknown to the library. + internal DocumentStreamInfo(string id, IReadOnlyList documentFilterGroups, IDictionary serializedAdditionalRawData) + { + Id = id; + DocumentFilterGroups = documentFilterGroups; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DocumentStreamInfo() + { + } + + /// Identifier of the document stream initiated by a UX. + public string Id { get; } + /// Gets or sets an OR-connected collection of filter groups. + public IReadOnlyList DocumentFilterGroups { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentType.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentType.cs new file mode 100644 index 000000000000..d0eec283fbcf --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/DocumentType.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Document type. + internal readonly partial struct DocumentType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DocumentType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string RequestValue = "Request"; + private const string RemoteDependencyValue = "RemoteDependency"; + private const string ExceptionValue = "Exception"; + private const string EventValue = "Event"; + private const string TraceValue = "Trace"; + private const string UnknownValue = "Unknown"; + + /// Represents a request telemetry type. + public static DocumentType Request { get; } = new DocumentType(RequestValue); + /// Represents a remote dependency telemetry type. + public static DocumentType RemoteDependency { get; } = new DocumentType(RemoteDependencyValue); + /// Represents an exception telemetry type. + public static DocumentType Exception { get; } = new DocumentType(ExceptionValue); + /// Represents an event telemetry type. + public static DocumentType Event { get; } = new DocumentType(EventValue); + /// Represents a trace telemetry type. + public static DocumentType Trace { get; } = new DocumentType(TraceValue); + /// Represents an unknown telemetry type. + public static DocumentType Unknown { get; } = new DocumentType(UnknownValue); + /// Determines if two values are the same. + public static bool operator ==(DocumentType left, DocumentType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DocumentType left, DocumentType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DocumentType(string value) => new DocumentType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DocumentType other && Equals(other); + /// + public bool Equals(DocumentType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Event.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Event.Serialization.cs new file mode 100644 index 000000000000..90d354ff457a --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Event.Serialization.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Event : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Event)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + } + } + + Event IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Event)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEvent(document.RootElement, options); + } + + internal static Event DeserializeEvent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Event(documentType, documentStreamIds ?? new ChangeTrackingList(), properties ?? new ChangeTrackingList(), serializedAdditionalRawData, name); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Event)} does not support writing '{options.Format}' format."); + } + } + + Event IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEvent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Event)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Event FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEvent(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Event.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Event.cs new file mode 100644 index 000000000000..ac0ba2ec5b66 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Event.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Event document type. + public partial class Event : DocumentIngress + { + /// Initializes a new instance of . + public Event() + { + DocumentType = DocumentType.Event; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Event name. + internal Event(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string name) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Name = name; + } + + /// Event name. + public string Name { get; set; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Exception.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Exception.Serialization.cs new file mode 100644 index 000000000000..4b1aba040a74 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Exception.Serialization.cs @@ -0,0 +1,185 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Exception : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Exception)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(ExceptionType)) + { + writer.WritePropertyName("ExceptionType"u8); + writer.WriteStringValue(ExceptionType); + } + if (Optional.IsDefined(ExceptionMessage)) + { + writer.WritePropertyName("ExceptionMessage"u8); + writer.WriteStringValue(ExceptionMessage); + } + } + + Exception IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Exception)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeException(document.RootElement, options); + } + + internal static Exception DeserializeException(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string exceptionType = default; + string exceptionMessage = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ExceptionType"u8)) + { + exceptionType = property.Value.GetString(); + continue; + } + if (property.NameEquals("ExceptionMessage"u8)) + { + exceptionMessage = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Exception( + documentType, + documentStreamIds ?? new ChangeTrackingList(), + properties ?? new ChangeTrackingList(), + serializedAdditionalRawData, + exceptionType, + exceptionMessage); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Exception)} does not support writing '{options.Format}' format."); + } + } + + Exception IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeException(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Exception)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Exception FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeException(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Exception.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Exception.cs new file mode 100644 index 000000000000..33c36b88e5e0 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Exception.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Exception document type. + public partial class Exception : DocumentIngress + { + /// Initializes a new instance of . + public Exception() + { + DocumentType = DocumentType.Exception; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Exception type name. + /// Exception message. + internal Exception(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string exceptionType, string exceptionMessage) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + ExceptionType = exceptionType; + ExceptionMessage = exceptionMessage; + } + + /// Exception type name. + public string ExceptionType { get; set; } + /// Exception message. + public string ExceptionMessage { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.Serialization.cs similarity index 63% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.Serialization.cs rename to sdk/applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.Serialization.cs index 5399705adc93..92240918d0d1 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.Serialization.cs +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.Serialization.cs @@ -9,15 +9,16 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure; using Azure.Core; -namespace Azure.AI.OpenAI.Assistants +namespace LiveMetrics { - internal partial class CreateAssistantFileRequest : IUtf8JsonSerializable, IJsonModel + public partial class FilterConjunctionGroupInfo : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,14 +29,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRe /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateAssistantFileRequest)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support writing '{format}' format."); } - writer.WritePropertyName("file_id"u8); - writer.WriteStringValue(FileId); + writer.WritePropertyName("Filters"u8); + writer.WriteStartArray(); + foreach (var item in Filters) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -53,19 +59,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - CreateAssistantFileRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FilterConjunctionGroupInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateAssistantFileRequest)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateAssistantFileRequest(document.RootElement, options); + return DeserializeFilterConjunctionGroupInfo(document.RootElement, options); } - internal static CreateAssistantFileRequest DeserializeCreateAssistantFileRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static FilterConjunctionGroupInfo DeserializeFilterConjunctionGroupInfo(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -73,14 +79,19 @@ internal static CreateAssistantFileRequest DeserializeCreateAssistantFileRequest { return null; } - string fileId = default; + IReadOnlyList filters = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("file_id"u8)) + if (property.NameEquals("Filters"u8)) { - fileId = property.Value.GetString(); + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FilterInfo.DeserializeFilterInfo(item, options)); + } + filters = array; continue; } if (options.Format != "W") @@ -89,46 +100,46 @@ internal static CreateAssistantFileRequest DeserializeCreateAssistantFileRequest } } serializedAdditionalRawData = rawDataDictionary; - return new CreateAssistantFileRequest(fileId, serializedAdditionalRawData); + return new FilterConjunctionGroupInfo(filters, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(CreateAssistantFileRequest)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support writing '{options.Format}' format."); } } - CreateAssistantFileRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + FilterConjunctionGroupInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateAssistantFileRequest(document.RootElement, options); + return DeserializeFilterConjunctionGroupInfo(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateAssistantFileRequest)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(FilterConjunctionGroupInfo)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateAssistantFileRequest FromResponse(Response response) + internal static FilterConjunctionGroupInfo FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateAssistantFileRequest(document.RootElement); + return DeserializeFilterConjunctionGroupInfo(document.RootElement); } /// Convert into a . diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.cs new file mode 100644 index 000000000000..16ce6d4a1f18 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterConjunctionGroupInfo.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// An AND-connected group of FilterInfo objects. + public partial class FilterConjunctionGroupInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// An array of filters. + /// is null. + internal FilterConjunctionGroupInfo(IEnumerable filters) + { + Argument.AssertNotNull(filters, nameof(filters)); + + Filters = filters.ToList(); + } + + /// Initializes a new instance of . + /// An array of filters. + /// Keeps track of any properties unknown to the library. + internal FilterConjunctionGroupInfo(IReadOnlyList filters, IDictionary serializedAdditionalRawData) + { + Filters = filters; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FilterConjunctionGroupInfo() + { + } + + /// An array of filters. + public IReadOnlyList Filters { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.Serialization.cs new file mode 100644 index 000000000000..fbf6a86762ca --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class FilterInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FilterInfo)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("FieldName"u8); + writer.WriteStringValue(FieldName); + writer.WritePropertyName("Predicate"u8); + writer.WriteStringValue(Predicate.ToString()); + writer.WritePropertyName("Comparand"u8); + writer.WriteStringValue(Comparand); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FilterInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FilterInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFilterInfo(document.RootElement, options); + } + + internal static FilterInfo DeserializeFilterInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fieldName = default; + PredicateType predicate = default; + string comparand = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("FieldName"u8)) + { + fieldName = property.Value.GetString(); + continue; + } + if (property.NameEquals("Predicate"u8)) + { + predicate = new PredicateType(property.Value.GetString()); + continue; + } + if (property.NameEquals("Comparand"u8)) + { + comparand = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FilterInfo(fieldName, predicate, comparand, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FilterInfo)} does not support writing '{options.Format}' format."); + } + } + + FilterInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFilterInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FilterInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FilterInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFilterInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.cs new file mode 100644 index 000000000000..227a405ba0cb --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/FilterInfo.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// A filter set on UX. + public partial class FilterInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// dimension name of the filter. + /// Operator of the filter. + /// Comparand of the filter. + /// or is null. + internal FilterInfo(string fieldName, PredicateType predicate, string comparand) + { + Argument.AssertNotNull(fieldName, nameof(fieldName)); + Argument.AssertNotNull(comparand, nameof(comparand)); + + FieldName = fieldName; + Predicate = predicate; + Comparand = comparand; + } + + /// Initializes a new instance of . + /// dimension name of the filter. + /// Operator of the filter. + /// Comparand of the filter. + /// Keeps track of any properties unknown to the library. + internal FilterInfo(string fieldName, PredicateType predicate, string comparand, IDictionary serializedAdditionalRawData) + { + FieldName = fieldName; + Predicate = predicate; + Comparand = comparand; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FilterInfo() + { + } + + /// dimension name of the filter. + public string FieldName { get; } + /// Operator of the filter. + public PredicateType Predicate { get; } + /// Comparand of the filter. + public string Comparand { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Argument.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..fd93d797ccdf --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace LiveMetrics +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..adba2e33ac67 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace LiveMetrics +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..d80288a80595 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..7c2e93f3723f --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace LiveMetrics +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Optional.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..eeab5e028d1a --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace LiveMetrics +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/BinaryContentHelper.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/RequestContentHelper.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/BinaryContentHelper.cs rename to sdk/applicationinsights/LiveMetrics/src/Generated/Internal/RequestContentHelper.cs index e5fd4d33e731..47773ff2f03c 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/BinaryContentHelper.cs +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/RequestContentHelper.cs @@ -1,20 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable using System; -using System.ClientModel; using System.Collections.Generic; using System.Text.Json; +using Azure.Core; -namespace Azure.AI.OpenAI +namespace LiveMetrics { - internal static partial class BinaryContentHelper + internal static class RequestContentHelper { - public static BinaryContent FromEnumerable(IEnumerable enumerable) - where T : notnull + public static RequestContent FromEnumerable(IEnumerable enumerable) + where T : notnull { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteStartArray(); foreach (var item in enumerable) { @@ -25,9 +28,9 @@ public static BinaryContent FromEnumerable(IEnumerable enumerable) return content; } - public static BinaryContent FromEnumerable(IEnumerable enumerable) + public static RequestContent FromEnumerable(IEnumerable enumerable) { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteStartArray(); foreach (var item in enumerable) { @@ -38,9 +41,9 @@ public static BinaryContent FromEnumerable(IEnumerable enumerable) else { #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item); + content.JsonWriter.WriteRawValue(item); #else - using (JsonDocument document = JsonDocument.Parse(item)) + using (JsonDocument document = JsonDocument.Parse(item, ModelSerializationExtensions.JsonDocumentOptions)) { JsonSerializer.Serialize(content.JsonWriter, document.RootElement); } @@ -52,13 +55,12 @@ public static BinaryContent FromEnumerable(IEnumerable enumerable) return content; } - public static BinaryContent FromEnumerable(ReadOnlySpan span) - where T : notnull + public static RequestContent FromEnumerable(ReadOnlySpan span) + where T : notnull { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteStartArray(); - int i = 0; - for (; i < span.Length; i++) + for (int i = 0; i < span.Length; i++) { content.JsonWriter.WriteObjectValue(span[i], ModelSerializationExtensions.WireOptions); } @@ -67,10 +69,10 @@ public static BinaryContent FromEnumerable(ReadOnlySpan span) return content; } - public static BinaryContent FromDictionary(IDictionary dictionary) - where TValue : notnull + public static RequestContent FromDictionary(IDictionary dictionary) + where TValue : notnull { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteStartObject(); foreach (var item in dictionary) { @@ -82,9 +84,9 @@ public static BinaryContent FromDictionary(IDictionary d return content; } - public static BinaryContent FromDictionary(IDictionary dictionary) + public static RequestContent FromDictionary(IDictionary dictionary) { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteStartObject(); foreach (var item in dictionary) { @@ -96,9 +98,9 @@ public static BinaryContent FromDictionary(IDictionary dicti else { #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(item.Value); + content.JsonWriter.WriteRawValue(item.Value); #else - using (JsonDocument document = JsonDocument.Parse(item.Value)) + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) { JsonSerializer.Serialize(content.JsonWriter, document.RootElement); } @@ -110,20 +112,20 @@ public static BinaryContent FromDictionary(IDictionary dicti return content; } - public static BinaryContent FromObject(object value) + public static RequestContent FromObject(object value) { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(value, ModelSerializationExtensions.WireOptions); return content; } - public static BinaryContent FromObject(BinaryData value) + public static RequestContent FromObject(BinaryData value) { - Utf8JsonBinaryContent content = new Utf8JsonBinaryContent(); + Utf8JsonRequestContent content = new Utf8JsonRequestContent(); #if NET6_0_OR_GREATER - content.JsonWriter.WriteRawValue(value); + content.JsonWriter.WriteRawValue(value); #else - using (JsonDocument document = JsonDocument.Parse(value)) + using (JsonDocument document = JsonDocument.Parse(value, ModelSerializationExtensions.JsonDocumentOptions)) { JsonSerializer.Serialize(content.JsonWriter, document.RootElement); } diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..0d748623b16d --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace LiveMetrics +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.Serialization.cs new file mode 100644 index 000000000000..50bb490722bf --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class KeyValuePairStringString : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + KeyValuePairStringString IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeKeyValuePairStringString(document.RootElement, options); + } + + internal static KeyValuePairStringString DeserializeKeyValuePairStringString(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + string value = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("value"u8)) + { + value = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new KeyValuePairStringString(key, value, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support writing '{options.Format}' format."); + } + } + + KeyValuePairStringString IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeKeyValuePairStringString(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(KeyValuePairStringString)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static KeyValuePairStringString FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeKeyValuePairStringString(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.cs new file mode 100644 index 000000000000..ebe35b0f0370 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/KeyValuePairStringString.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Key-value pair of string and string. + public partial class KeyValuePairStringString + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Key of the key-value pair. + /// Value of the key-value pair. + /// or is null. + public KeyValuePairStringString(string key, string value) + { + Argument.AssertNotNull(key, nameof(key)); + Argument.AssertNotNull(value, nameof(value)); + + Key = key; + Value = value; + } + + /// Initializes a new instance of . + /// Key of the key-value pair. + /// Value of the key-value pair. + /// Keeps track of any properties unknown to the library. + internal KeyValuePairStringString(string key, string value, IDictionary serializedAdditionalRawData) + { + Key = key; + Value = value; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal KeyValuePairStringString() + { + } + + /// Key of the key-value pair. + public string Key { get; } + /// Value of the key-value pair. + public string Value { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClient.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClient.cs new file mode 100644 index 000000000000..48b465ab2013 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClient.cs @@ -0,0 +1,408 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace LiveMetrics +{ + // Data plane generated client. + /// Live Metrics REST APIs. + public partial class LiveMetricsClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://monitor.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of LiveMetricsClient for mocking. + protected LiveMetricsClient() + { + } + + /// Initializes a new instance of LiveMetricsClient. + /// A credential used to authenticate to an Azure Service. + /// is null. + public LiveMetricsClient(TokenCredential credential) : this(new Uri("https://global.livediagnostics.monitor.azure.com"), credential, new LiveMetricsClientOptions()) + { + } + + /// Initializes a new instance of LiveMetricsClient. + /// The endpoint of the Live Metrics service. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public LiveMetricsClient(Uri endpoint, TokenCredential credential, LiveMetricsClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new LiveMetricsClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Determine whether there is any subscription to the metrics and documents. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between Application Insights client SDK and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> IsSubscribedAsync(string ikey, MonitoringDataPoint monitoringDataPoint = null, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoint?.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await IsSubscribedAsync(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context).ConfigureAwait(false); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// Determine whether there is any subscription to the metrics and documents. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between Application Insights client SDK and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The cancellation token to use. + /// is null. + /// + public virtual Response IsSubscribed(string ikey, MonitoringDataPoint monitoringDataPoint = null, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoint?.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = IsSubscribed(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// + /// [Protocol Method] Determine whether there is any subscription to the metrics and documents. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task IsSubscribedAsync(string ikey, RequestContent content, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.IsSubscribed"); + scope.Start(); + try + { + using HttpMessage message = CreateIsSubscribedRequest(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Determine whether there is any subscription to the metrics and documents. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// Computer name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Service instance name where Application Insights SDK lives. Live Metrics uses machine name with instance name as a backup. + /// Identifies an Application Insights SDK as trusted agent to report metrics and documents. + /// Cloud role name of the service. + /// Version/generation of the data contract (MonitoringDataPoint) between the client and Live Metrics. + /// An encoded string that indicates whether the collection configuration is changed. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response IsSubscribed(string ikey, RequestContent content, long? transmissionTime = null, string machineName = null, string instanceName = null, string streamId = null, string roleName = null, string invariantVersion = null, ETag? configurationEtag = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.IsSubscribed"); + scope.Start(); + try + { + using HttpMessage message = CreateIsSubscribedRequest(ikey, content, transmissionTime, machineName, instanceName, streamId, roleName, invariantVersion, configurationEtag, context); + return _pipeline.ProcessMessage(message, context); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between the client and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The cancellation token to use. + /// is null. + /// + public virtual async Task> PublishAsync(string ikey, IEnumerable monitoringDataPoints = null, ETag? configurationEtag = null, long? transmissionTime = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoints != null ? RequestContentHelper.FromEnumerable(monitoringDataPoints) : null; + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await PublishAsync(ikey, content, configurationEtag, transmissionTime, context).ConfigureAwait(false); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// Data contract between the client and Live Metrics. /QuickPulseService.svc/ping uses this as a backup source of machine name, instance name and invariant version. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The cancellation token to use. + /// is null. + /// + public virtual Response Publish(string ikey, IEnumerable monitoringDataPoints = null, ETag? configurationEtag = null, long? transmissionTime = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using RequestContent content = monitoringDataPoints != null ? RequestContentHelper.FromEnumerable(monitoringDataPoints) : null; + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Publish(ikey, content, configurationEtag, transmissionTime, context); + return Response.FromValue(CollectionConfigurationInfo.FromResponse(response), response); + } + + /// + /// [Protocol Method] Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task PublishAsync(string ikey, RequestContent content, ETag? configurationEtag = null, long? transmissionTime = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.Publish"); + scope.Start(); + try + { + using HttpMessage message = CreatePublishRequest(ikey, content, configurationEtag, transmissionTime, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Publish live metrics to the Live Metrics service when there is an active subscription to the metrics. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The instrumentation key of the target Application Insights component for which the client checks whether there's any subscription to it. + /// The content to send as the body of the request. + /// An encoded string that indicates whether the collection configuration is changed. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. A 8-byte long type of ticks. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Publish(string ikey, RequestContent content, ETag? configurationEtag = null, long? transmissionTime = null, RequestContext context = null) + { + Argument.AssertNotNull(ikey, nameof(ikey)); + + using var scope = ClientDiagnostics.CreateScope("LiveMetricsClient.Publish"); + scope.Start(); + try + { + using HttpMessage message = CreatePublishRequest(ikey, content, configurationEtag, transmissionTime, context); + return _pipeline.ProcessMessage(message, context); + } + catch (System.Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateIsSubscribedRequest(string ikey, RequestContent content, long? transmissionTime, string machineName, string instanceName, string streamId, string roleName, string invariantVersion, ETag? configurationEtag, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/QuickPulseService.svc/ping", false); + uri.AppendQuery("ikey", ikey, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (transmissionTime != null) + { + request.Headers.Add("x-ms-qps-transmission-time", transmissionTime.Value); + } + if (machineName != null) + { + request.Headers.Add("x-ms-qps-machine-name", machineName); + } + if (instanceName != null) + { + request.Headers.Add("x-ms-qps-instance-name", instanceName); + } + if (streamId != null) + { + request.Headers.Add("x-ms-qps-stream-id", streamId); + } + if (roleName != null) + { + request.Headers.Add("x-ms-qps-role-name", roleName); + } + if (invariantVersion != null) + { + request.Headers.Add("x-ms-qps-invariant-version", invariantVersion); + } + if (configurationEtag != null) + { + request.Headers.Add("x-ms-qps-configuration-etag", configurationEtag.Value); + } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreatePublishRequest(string ikey, RequestContent content, ETag? configurationEtag, long? transmissionTime, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/QuickPulseService.svc/post", false); + uri.AppendQuery("ikey", ikey, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (configurationEtag != null) + { + request.Headers.Add("x-ms-qps-configuration-etag", configurationEtag.Value); + } + if (transmissionTime != null) + { + request.Headers.Add("x-ms-qps-transmission-time", transmissionTime.Value); + } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientBuilderExtensions.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientBuilderExtensions.cs new file mode 100644 index 000000000000..8ecb9e953fd2 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core.Extensions; +using LiveMetrics; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class LiveMetricsClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The endpoint of the Live Metrics service. + public static IAzureClientBuilder AddLiveMetricsClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new LiveMetricsClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddLiveMetricsClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientOptions.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientOptions.cs new file mode 100644 index 000000000000..570f16b4a1b1 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace LiveMetrics +{ + /// Client options for LiveMetricsClient. + public partial class LiveMetricsClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2024_04_01_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2024-04-01-preview". + V2024_04_01_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of LiveMetricsClientOptions. + public LiveMetricsClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2024_04_01_Preview => "2024-04-01-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsModelFactory.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsModelFactory.cs new file mode 100644 index 000000000000..512a865451bb --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/LiveMetricsModelFactory.cs @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiveMetrics +{ + /// Model factory for models. + public static partial class LiveMetricsModelFactory + { + /// Initializes a new instance of . + /// Application Insights SDK version. + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + /// Service instance name where Application Insights SDK lives. + /// Service role name. + /// Computer name where Application Insights SDK lives. + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + /// Data point generation timestamp. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. + /// True if the current application is an Azure Web App. + /// True if performance counters collection is supported. + /// An array of metric data points. + /// + /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace} + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// An array of top cpu consumption data point. + /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics. + /// A new instance for mocking. + public static MonitoringDataPoint MonitoringDataPoint(string version = null, int invariantVersion = default, string instance = null, string roleName = null, string machineName = null, string streamId = null, DateTimeOffset? timestamp = null, DateTimeOffset? transmissionTime = null, bool isWebApp = default, bool performanceCollectionSupported = default, IEnumerable metrics = null, IEnumerable documents = null, IEnumerable topCpuProcesses = null, IEnumerable collectionConfigurationErrors = null) + { + metrics ??= new List(); + documents ??= new List(); + topCpuProcesses ??= new List(); + collectionConfigurationErrors ??= new List(); + + return new MonitoringDataPoint( + version, + invariantVersion, + instance, + roleName, + machineName, + streamId, + timestamp, + transmissionTime, + isWebApp, + performanceCollectionSupported, + metrics?.ToList(), + documents?.ToList(), + topCpuProcesses?.ToList(), + collectionConfigurationErrors?.ToList(), + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// An encoded string that indicates whether the collection configuration is changed. + /// An array of metric configuration info. + /// An array of document stream configuration info. + /// Controls document quotas to be sent to Live Metrics. + /// A new instance for mocking. + public static CollectionConfigurationInfo CollectionConfigurationInfo(string eTag = null, IEnumerable metrics = null, IEnumerable documentStreams = null, QuotaConfigurationInfo quotaInfo = null) + { + metrics ??= new List(); + documentStreams ??= new List(); + + return new CollectionConfigurationInfo(eTag, metrics?.ToList(), documentStreams?.ToList(), quotaInfo, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// metric configuration identifier. + /// Telemetry type. + /// A collection of filters to scope metrics that UX needs. + /// Telemetry's metric dimension whose value is to be aggregated. Example values: Duration, Count(),... + /// Aggregation type. This is the aggregation done from everything within a single server. + /// Aggregation type. This Aggregation is done across the values for all the servers taken together. + /// A new instance for mocking. + public static DerivedMetricInfo DerivedMetricInfo(string id = null, string telemetryType = null, IEnumerable filterGroups = null, string projection = null, AggregationType aggregation = default, AggregationType backEndAggregation = default) + { + filterGroups ??= new List(); + + return new DerivedMetricInfo( + id, + telemetryType, + filterGroups?.ToList(), + projection, + aggregation, + backEndAggregation, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// An array of filters. + /// A new instance for mocking. + public static FilterConjunctionGroupInfo FilterConjunctionGroupInfo(IEnumerable filters = null) + { + filters ??= new List(); + + return new FilterConjunctionGroupInfo(filters?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// dimension name of the filter. + /// Operator of the filter. + /// Comparand of the filter. + /// A new instance for mocking. + public static FilterInfo FilterInfo(string fieldName = null, PredicateType predicate = default, string comparand = null) + { + return new FilterInfo(fieldName, predicate, comparand, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Identifier of the document stream initiated by a UX. + /// Gets or sets an OR-connected collection of filter groups. + /// A new instance for mocking. + public static DocumentStreamInfo DocumentStreamInfo(string id = null, IEnumerable documentFilterGroups = null) + { + documentFilterGroups ??= new List(); + + return new DocumentStreamInfo(id, documentFilterGroups?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Telemetry type. + /// An array of filter groups. + /// A new instance for mocking. + public static DocumentFilterConjunctionGroupInfo DocumentFilterConjunctionGroupInfo(TelemetryType telemetryType = default, FilterConjunctionGroupInfo filters = null) + { + return new DocumentFilterConjunctionGroupInfo(telemetryType, filters, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Initial quota. + /// Max quota. + /// Quota accrual rate per second. + /// A new instance for mocking. + public static QuotaConfigurationInfo QuotaConfigurationInfo(float? initialQuota = null, float maxQuota = default, float quotaAccrualRatePerSec = default) + { + return new QuotaConfigurationInfo(initialQuota, maxQuota, quotaAccrualRatePerSec, serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/MetricPoint.Serialization.cs similarity index 64% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.Serialization.cs rename to sdk/applicationinsights/LiveMetrics/src/Generated/MetricPoint.Serialization.cs index bae85ab90a4f..69f7df78a2e8 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.Serialization.cs +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/MetricPoint.Serialization.cs @@ -9,15 +9,16 @@ using System.ClientModel.Primitives; using System.Collections.Generic; using System.Text.Json; +using Azure; using Azure.Core; -namespace Azure.AI.OpenAI.Assistants +namespace LiveMetrics { - public partial class MessageFile : IUtf8JsonSerializable, IJsonModel + public partial class MetricPoint : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,20 +29,18 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptio /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(MessageFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(MetricPoint)} does not support writing '{format}' format."); } - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object); - writer.WritePropertyName("created_at"u8); - writer.WriteNumberValue(CreatedAt, "U"); - writer.WritePropertyName("message_id"u8); - writer.WriteStringValue(MessageId); + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("Value"u8); + writer.WriteNumberValue(Value); + writer.WritePropertyName("Weight"u8); + writer.WriteNumberValue(Weight); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -59,19 +58,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - MessageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + MetricPoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(MessageFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(MetricPoint)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeMessageFile(document.RootElement, options); + return DeserializeMetricPoint(document.RootElement, options); } - internal static MessageFile DeserializeMessageFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static MetricPoint DeserializeMetricPoint(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,32 +78,26 @@ internal static MessageFile DeserializeMessageFile(JsonElement element, ModelRea { return null; } - string id = default; - string @object = default; - DateTimeOffset createdAt = default; - string messageId = default; + string name = default; + double value = default; + int weight = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("Name"u8)) { - id = property.Value.GetString(); + name = property.Value.GetString(); continue; } - if (property.NameEquals("object"u8)) + if (property.NameEquals("Value"u8)) { - @object = property.Value.GetString(); + value = property.Value.GetDouble(); continue; } - if (property.NameEquals("created_at"u8)) + if (property.NameEquals("Weight"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); - continue; - } - if (property.NameEquals("message_id"u8)) - { - messageId = property.Value.GetString(); + weight = property.Value.GetInt32(); continue; } if (options.Format != "W") @@ -113,46 +106,46 @@ internal static MessageFile DeserializeMessageFile(JsonElement element, ModelRea } } serializedAdditionalRawData = rawDataDictionary; - return new MessageFile(id, @object, createdAt, messageId, serializedAdditionalRawData); + return new MetricPoint(name, value, weight, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(MessageFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(MetricPoint)} does not support writing '{options.Format}' format."); } } - MessageFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + MetricPoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeMessageFile(document.RootElement, options); + return DeserializeMetricPoint(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(MessageFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(MetricPoint)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static MessageFile FromResponse(Response response) + internal static MetricPoint FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeMessageFile(document.RootElement); + return DeserializeMetricPoint(document.RootElement); } /// Convert into a . diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/MetricPoint.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/MetricPoint.cs new file mode 100644 index 000000000000..8c523231a237 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/MetricPoint.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Metric data point. + public partial class MetricPoint + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Metric name. + /// Metric value. + /// Metric weight. + /// is null. + public MetricPoint(string name, double value, int weight) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + Value = value; + Weight = weight; + } + + /// Initializes a new instance of . + /// Metric name. + /// Metric value. + /// Metric weight. + /// Keeps track of any properties unknown to the library. + internal MetricPoint(string name, double value, int weight, IDictionary serializedAdditionalRawData) + { + Name = name; + Value = value; + Weight = weight; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MetricPoint() + { + } + + /// Metric name. + public string Name { get; } + /// Metric value. + public double Value { get; } + /// Metric weight. + public int Weight { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.Serialization.cs new file mode 100644 index 000000000000..92883288f97d --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.Serialization.cs @@ -0,0 +1,344 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class MonitoringDataPoint : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("Version"u8); + writer.WriteStringValue(Version); + writer.WritePropertyName("InvariantVersion"u8); + writer.WriteNumberValue(InvariantVersion); + writer.WritePropertyName("Instance"u8); + writer.WriteStringValue(Instance); + writer.WritePropertyName("RoleName"u8); + writer.WriteStringValue(RoleName); + writer.WritePropertyName("MachineName"u8); + writer.WriteStringValue(MachineName); + writer.WritePropertyName("StreamId"u8); + writer.WriteStringValue(StreamId); + if (Optional.IsDefined(Timestamp)) + { + writer.WritePropertyName("Timestamp"u8); + writer.WriteStringValue(Timestamp.Value, "O"); + } + if (Optional.IsDefined(TransmissionTime)) + { + writer.WritePropertyName("TransmissionTime"u8); + writer.WriteStringValue(TransmissionTime.Value, "O"); + } + writer.WritePropertyName("IsWebApp"u8); + writer.WriteBooleanValue(IsWebApp); + writer.WritePropertyName("PerformanceCollectionSupported"u8); + writer.WriteBooleanValue(PerformanceCollectionSupported); + if (Optional.IsCollectionDefined(Metrics)) + { + writer.WritePropertyName("Metrics"u8); + writer.WriteStartArray(); + foreach (var item in Metrics) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Documents)) + { + writer.WritePropertyName("Documents"u8); + writer.WriteStartArray(); + foreach (var item in Documents) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(TopCpuProcesses)) + { + writer.WritePropertyName("TopCpuProcesses"u8); + writer.WriteStartArray(); + foreach (var item in TopCpuProcesses) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(CollectionConfigurationErrors)) + { + writer.WritePropertyName("CollectionConfigurationErrors"u8); + writer.WriteStartArray(); + foreach (var item in CollectionConfigurationErrors) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MonitoringDataPoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMonitoringDataPoint(document.RootElement, options); + } + + internal static MonitoringDataPoint DeserializeMonitoringDataPoint(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string version = default; + int invariantVersion = default; + string instance = default; + string roleName = default; + string machineName = default; + string streamId = default; + DateTimeOffset? timestamp = default; + DateTimeOffset? transmissionTime = default; + bool isWebApp = default; + bool performanceCollectionSupported = default; + IList metrics = default; + IList documents = default; + IList topCpuProcesses = default; + IList collectionConfigurationErrors = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Version"u8)) + { + version = property.Value.GetString(); + continue; + } + if (property.NameEquals("InvariantVersion"u8)) + { + invariantVersion = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("Instance"u8)) + { + instance = property.Value.GetString(); + continue; + } + if (property.NameEquals("RoleName"u8)) + { + roleName = property.Value.GetString(); + continue; + } + if (property.NameEquals("MachineName"u8)) + { + machineName = property.Value.GetString(); + continue; + } + if (property.NameEquals("StreamId"u8)) + { + streamId = property.Value.GetString(); + continue; + } + if (property.NameEquals("Timestamp"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + timestamp = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("TransmissionTime"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + transmissionTime = property.Value.GetDateTimeOffset("O"); + continue; + } + if (property.NameEquals("IsWebApp"u8)) + { + isWebApp = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("PerformanceCollectionSupported"u8)) + { + performanceCollectionSupported = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("Metrics"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(MetricPoint.DeserializeMetricPoint(item, options)); + } + metrics = array; + continue; + } + if (property.NameEquals("Documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(DocumentIngress.DeserializeDocumentIngress(item, options)); + } + documents = array; + continue; + } + if (property.NameEquals("TopCpuProcesses"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ProcessCpuData.DeserializeProcessCpuData(item, options)); + } + topCpuProcesses = array; + continue; + } + if (property.NameEquals("CollectionConfigurationErrors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(CollectionConfigurationError.DeserializeCollectionConfigurationError(item, options)); + } + collectionConfigurationErrors = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MonitoringDataPoint( + version, + invariantVersion, + instance, + roleName, + machineName, + streamId, + timestamp, + transmissionTime, + isWebApp, + performanceCollectionSupported, + metrics ?? new ChangeTrackingList(), + documents ?? new ChangeTrackingList(), + topCpuProcesses ?? new ChangeTrackingList(), + collectionConfigurationErrors ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support writing '{options.Format}' format."); + } + } + + MonitoringDataPoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMonitoringDataPoint(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MonitoringDataPoint)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MonitoringDataPoint FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMonitoringDataPoint(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.cs new file mode 100644 index 000000000000..5198042c9af1 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/MonitoringDataPoint.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Monitoring data point coming from the client, which includes metrics, documents and other metadata info. + public partial class MonitoringDataPoint + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Application Insights SDK version. + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + /// Service instance name where Application Insights SDK lives. + /// Service role name. + /// Computer name where Application Insights SDK lives. + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + /// True if the current application is an Azure Web App. + /// True if performance counters collection is supported. + /// , , , or is null. + public MonitoringDataPoint(string version, int invariantVersion, string instance, string roleName, string machineName, string streamId, bool isWebApp, bool performanceCollectionSupported) + { + Argument.AssertNotNull(version, nameof(version)); + Argument.AssertNotNull(instance, nameof(instance)); + Argument.AssertNotNull(roleName, nameof(roleName)); + Argument.AssertNotNull(machineName, nameof(machineName)); + Argument.AssertNotNull(streamId, nameof(streamId)); + + Version = version; + InvariantVersion = invariantVersion; + Instance = instance; + RoleName = roleName; + MachineName = machineName; + StreamId = streamId; + IsWebApp = isWebApp; + PerformanceCollectionSupported = performanceCollectionSupported; + Metrics = new ChangeTrackingList(); + Documents = new ChangeTrackingList(); + TopCpuProcesses = new ChangeTrackingList(); + CollectionConfigurationErrors = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// Application Insights SDK version. + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + /// Service instance name where Application Insights SDK lives. + /// Service role name. + /// Computer name where Application Insights SDK lives. + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + /// Data point generation timestamp. + /// Timestamp when the client transmits the metrics and documents to Live Metrics. + /// True if the current application is an Azure Web App. + /// True if performance counters collection is supported. + /// An array of metric data points. + /// + /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace} + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// An array of top cpu consumption data point. + /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics. + /// Keeps track of any properties unknown to the library. + internal MonitoringDataPoint(string version, int invariantVersion, string instance, string roleName, string machineName, string streamId, DateTimeOffset? timestamp, DateTimeOffset? transmissionTime, bool isWebApp, bool performanceCollectionSupported, IList metrics, IList documents, IList topCpuProcesses, IList collectionConfigurationErrors, IDictionary serializedAdditionalRawData) + { + Version = version; + InvariantVersion = invariantVersion; + Instance = instance; + RoleName = roleName; + MachineName = machineName; + StreamId = streamId; + Timestamp = timestamp; + TransmissionTime = transmissionTime; + IsWebApp = isWebApp; + PerformanceCollectionSupported = performanceCollectionSupported; + Metrics = metrics; + Documents = documents; + TopCpuProcesses = topCpuProcesses; + CollectionConfigurationErrors = collectionConfigurationErrors; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MonitoringDataPoint() + { + } + + /// Application Insights SDK version. + public string Version { get; } + /// Version/generation of the data contract (MonitoringDataPoint) between SDK and Live Metrics. + public int InvariantVersion { get; } + /// Service instance name where Application Insights SDK lives. + public string Instance { get; } + /// Service role name. + public string RoleName { get; } + /// Computer name where Application Insights SDK lives. + public string MachineName { get; } + /// Identifies an Application Insights SDK as a trusted agent to report metrics and documents. + public string StreamId { get; } + /// Data point generation timestamp. + public DateTimeOffset? Timestamp { get; set; } + /// Timestamp when the client transmits the metrics and documents to Live Metrics. + public DateTimeOffset? TransmissionTime { get; set; } + /// True if the current application is an Azure Web App. + public bool IsWebApp { get; } + /// True if performance counters collection is supported. + public bool PerformanceCollectionSupported { get; } + /// An array of metric data points. + public IList Metrics { get; } + /// + /// An array of documents of a specific type {Request}, {RemoteDependency}, {Exception}, {Event}, or {Trace} + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public IList Documents { get; } + /// An array of top cpu consumption data point. + public IList TopCpuProcesses { get; } + /// An array of error while SDK parses and applies the {CollectionConfigurationInfo} provided by Live Metrics. + public IList CollectionConfigurationErrors { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/PredicateType.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/PredicateType.cs new file mode 100644 index 000000000000..1804309fc4e3 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/PredicateType.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Enum representing the different types of predicates. + public readonly partial struct PredicateType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PredicateType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EqualValue = "Equal"; + private const string NotEqualValue = "NotEqual"; + private const string LessThanValue = "LessThan"; + private const string GreaterThanValue = "GreaterThan"; + private const string LessThanOrEqualValue = "LessThanOrEqual"; + private const string GreaterThanOrEqualValue = "GreaterThanOrEqual"; + private const string ContainsValue = "Contains"; + private const string DoesNotContainValue = "DoesNotContain"; + + /// Represents an equality predicate. + public static PredicateType Equal { get; } = new PredicateType(EqualValue); + /// Represents a not-equal predicate. + public static PredicateType NotEqual { get; } = new PredicateType(NotEqualValue); + /// Represents a less-than predicate. + public static PredicateType LessThan { get; } = new PredicateType(LessThanValue); + /// Represents a greater-than predicate. + public static PredicateType GreaterThan { get; } = new PredicateType(GreaterThanValue); + /// Represents a less-than-or-equal predicate. + public static PredicateType LessThanOrEqual { get; } = new PredicateType(LessThanOrEqualValue); + /// Represents a greater-than-or-equal predicate. + public static PredicateType GreaterThanOrEqual { get; } = new PredicateType(GreaterThanOrEqualValue); + /// Represents a contains predicate. + public static PredicateType Contains { get; } = new PredicateType(ContainsValue); + /// Represents a does-not-contain predicate. + public static PredicateType DoesNotContain { get; } = new PredicateType(DoesNotContainValue); + /// Determines if two values are the same. + public static bool operator ==(PredicateType left, PredicateType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PredicateType left, PredicateType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator PredicateType(string value) => new PredicateType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PredicateType other && Equals(other); + /// + public bool Equals(PredicateType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.Serialization.cs new file mode 100644 index 000000000000..9b4e00bb6763 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class ProcessCpuData : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("ProcessName"u8); + writer.WriteStringValue(ProcessName); + writer.WritePropertyName("CpuPercentage"u8); + writer.WriteNumberValue(CpuPercentage); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ProcessCpuData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeProcessCpuData(document.RootElement, options); + } + + internal static ProcessCpuData DeserializeProcessCpuData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string processName = default; + int cpuPercentage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ProcessName"u8)) + { + processName = property.Value.GetString(); + continue; + } + if (property.NameEquals("CpuPercentage"u8)) + { + cpuPercentage = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ProcessCpuData(processName, cpuPercentage, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support writing '{options.Format}' format."); + } + } + + ProcessCpuData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeProcessCpuData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ProcessCpuData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ProcessCpuData FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeProcessCpuData(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.cs new file mode 100644 index 000000000000..c4f1d9457d5e --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/ProcessCpuData.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// CPU consumption datapoint. + public partial class ProcessCpuData + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Process name. + /// CPU consumption percentage. + /// is null. + public ProcessCpuData(string processName, int cpuPercentage) + { + Argument.AssertNotNull(processName, nameof(processName)); + + ProcessName = processName; + CpuPercentage = cpuPercentage; + } + + /// Initializes a new instance of . + /// Process name. + /// CPU consumption percentage. + /// Keeps track of any properties unknown to the library. + internal ProcessCpuData(string processName, int cpuPercentage, IDictionary serializedAdditionalRawData) + { + ProcessName = processName; + CpuPercentage = cpuPercentage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ProcessCpuData() + { + } + + /// Process name. + public string ProcessName { get; } + /// CPU consumption percentage. + public int CpuPercentage { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.Serialization.cs new file mode 100644 index 000000000000..b1a07edabdee --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class QuotaConfigurationInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(InitialQuota)) + { + writer.WritePropertyName("InitialQuota"u8); + writer.WriteNumberValue(InitialQuota.Value); + } + writer.WritePropertyName("MaxQuota"u8); + writer.WriteNumberValue(MaxQuota); + writer.WritePropertyName("QuotaAccrualRatePerSec"u8); + writer.WriteNumberValue(QuotaAccrualRatePerSec); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + QuotaConfigurationInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeQuotaConfigurationInfo(document.RootElement, options); + } + + internal static QuotaConfigurationInfo DeserializeQuotaConfigurationInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + float? initialQuota = default; + float maxQuota = default; + float quotaAccrualRatePerSec = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("InitialQuota"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + initialQuota = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("MaxQuota"u8)) + { + maxQuota = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("QuotaAccrualRatePerSec"u8)) + { + quotaAccrualRatePerSec = property.Value.GetSingle(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new QuotaConfigurationInfo(initialQuota, maxQuota, quotaAccrualRatePerSec, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support writing '{options.Format}' format."); + } + } + + QuotaConfigurationInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeQuotaConfigurationInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(QuotaConfigurationInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static QuotaConfigurationInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeQuotaConfigurationInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.cs new file mode 100644 index 000000000000..3c09c73551fb --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/QuotaConfigurationInfo.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Controls document quotas to be sent to Live Metrics. + public partial class QuotaConfigurationInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Max quota. + /// Quota accrual rate per second. + internal QuotaConfigurationInfo(float maxQuota, float quotaAccrualRatePerSec) + { + MaxQuota = maxQuota; + QuotaAccrualRatePerSec = quotaAccrualRatePerSec; + } + + /// Initializes a new instance of . + /// Initial quota. + /// Max quota. + /// Quota accrual rate per second. + /// Keeps track of any properties unknown to the library. + internal QuotaConfigurationInfo(float? initialQuota, float maxQuota, float quotaAccrualRatePerSec, IDictionary serializedAdditionalRawData) + { + InitialQuota = initialQuota; + MaxQuota = maxQuota; + QuotaAccrualRatePerSec = quotaAccrualRatePerSec; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal QuotaConfigurationInfo() + { + } + + /// Initial quota. + public float? InitialQuota { get; } + /// Max quota. + public float MaxQuota { get; } + /// Quota accrual rate per second. + public float QuotaAccrualRatePerSec { get; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.Serialization.cs new file mode 100644 index 000000000000..35362a1356ff --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.Serialization.cs @@ -0,0 +1,209 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class RemoteDependency : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RemoteDependency)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(CommandName)) + { + writer.WritePropertyName("CommandName"u8); + writer.WriteStringValue(CommandName); + } + if (Optional.IsDefined(ResultCode)) + { + writer.WritePropertyName("ResultCode"u8); + writer.WriteStringValue(ResultCode); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("Duration"u8); + writer.WriteStringValue(Duration); + } + } + + RemoteDependency IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RemoteDependency)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRemoteDependency(document.RootElement, options); + } + + internal static RemoteDependency DeserializeRemoteDependency(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string commandName = default; + string resultCode = default; + string duration = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("CommandName"u8)) + { + commandName = property.Value.GetString(); + continue; + } + if (property.NameEquals("ResultCode"u8)) + { + resultCode = property.Value.GetString(); + continue; + } + if (property.NameEquals("Duration"u8)) + { + duration = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RemoteDependency( + documentType, + documentStreamIds ?? new ChangeTrackingList(), + properties ?? new ChangeTrackingList(), + serializedAdditionalRawData, + name, + commandName, + resultCode, + duration); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RemoteDependency)} does not support writing '{options.Format}' format."); + } + } + + RemoteDependency IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRemoteDependency(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RemoteDependency)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RemoteDependency FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRemoteDependency(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.cs new file mode 100644 index 000000000000..6cab0e3ad447 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/RemoteDependency.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// RemoteDependency document type. + public partial class RemoteDependency : DocumentIngress + { + /// Initializes a new instance of . + public RemoteDependency() + { + DocumentType = DocumentType.RemoteDependency; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Name of the command initiated with this dependency call, e.g., GET /username. + /// URL of the dependency call to the target, with all query string parameters. + /// Result code of a dependency call. Examples are SQL error code and HTTP status code. + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + internal RemoteDependency(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string name, string commandName, string resultCode, string duration) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Name = name; + CommandName = commandName; + ResultCode = resultCode; + Duration = duration; + } + + /// Name of the command initiated with this dependency call, e.g., GET /username. + public string Name { get; set; } + /// URL of the dependency call to the target, with all query string parameters. + public string CommandName { get; set; } + /// Result code of a dependency call. Examples are SQL error code and HTTP status code. + public string ResultCode { get; set; } + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + public string Duration { get; set; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Request.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Request.Serialization.cs new file mode 100644 index 000000000000..79dc2e9ccec8 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Request.Serialization.cs @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Request : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Request)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("Name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(Url)) + { + writer.WritePropertyName("Url"u8); + writer.WriteStringValue(Url.AbsoluteUri); + } + if (Optional.IsDefined(ResponseCode)) + { + writer.WritePropertyName("ResponseCode"u8); + writer.WriteStringValue(ResponseCode); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("Duration"u8); + writer.WriteStringValue(Duration); + } + } + + Request IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Request)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRequest(document.RootElement, options); + } + + internal static Request DeserializeRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + Uri url = default; + string responseCode = default; + string duration = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("Url"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + url = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("ResponseCode"u8)) + { + responseCode = property.Value.GetString(); + continue; + } + if (property.NameEquals("Duration"u8)) + { + duration = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Request( + documentType, + documentStreamIds ?? new ChangeTrackingList(), + properties ?? new ChangeTrackingList(), + serializedAdditionalRawData, + name, + url, + responseCode, + duration); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Request)} does not support writing '{options.Format}' format."); + } + } + + Request IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Request)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Request FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Request.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Request.cs new file mode 100644 index 000000000000..98ccc03686b9 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Request.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Request document type. + public partial class Request : DocumentIngress + { + /// Initializes a new instance of . + public Request() + { + DocumentType = DocumentType.Request; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Name of the request, e.g., 'GET /values/{id}'. + /// Request URL with all query string parameters. + /// Result of a request execution. For http requests, it could be some HTTP status code. + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + internal Request(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string name, Uri url, string responseCode, string duration) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Name = name; + Url = url; + ResponseCode = responseCode; + Duration = duration; + } + + /// Name of the request, e.g., 'GET /values/{id}'. + public string Name { get; set; } + /// Request URL with all query string parameters. + public Uri Url { get; set; } + /// Result of a request execution. For http requests, it could be some HTTP status code. + public string ResponseCode { get; set; } + /// Request duration in ISO 8601 duration format, i.e., P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W. + public string Duration { get; set; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/TelemetryType.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/TelemetryType.cs new file mode 100644 index 000000000000..9d35769389dc --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/TelemetryType.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace LiveMetrics +{ + /// Telemetry type. + public readonly partial struct TelemetryType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TelemetryType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string RequestValue = "Request"; + private const string DependencyValue = "Dependency"; + private const string ExceptionValue = "Exception"; + private const string EventValue = "Event"; + private const string MetricValue = "Metric"; + private const string PerformanceCounterValue = "PerformanceCounter"; + private const string TraceValue = "Trace"; + + /// Represents a request telemetry type. + public static TelemetryType Request { get; } = new TelemetryType(RequestValue); + /// Represents a dependency telemetry type. + public static TelemetryType Dependency { get; } = new TelemetryType(DependencyValue); + /// Represents an exception telemetry type. + public static TelemetryType Exception { get; } = new TelemetryType(ExceptionValue); + /// Represents an event telemetry type. + public static TelemetryType Event { get; } = new TelemetryType(EventValue); + /// Represents a metric telemetry type. + public static TelemetryType Metric { get; } = new TelemetryType(MetricValue); + /// Represents a performance counter telemetry type. + public static TelemetryType PerformanceCounter { get; } = new TelemetryType(PerformanceCounterValue); + /// Represents a trace telemetry type. + public static TelemetryType Trace { get; } = new TelemetryType(TraceValue); + /// Determines if two values are the same. + public static bool operator ==(TelemetryType left, TelemetryType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TelemetryType left, TelemetryType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TelemetryType(string value) => new TelemetryType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TelemetryType other && Equals(other); + /// + public bool Equals(TelemetryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Trace.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Trace.Serialization.cs new file mode 100644 index 000000000000..2eb7320d2bbf --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Trace.Serialization.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + public partial class Trace : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Trace)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Message)) + { + writer.WritePropertyName("Message"u8); + writer.WriteStringValue(Message); + } + } + + Trace IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Trace)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeTrace(document.RootElement, options); + } + + internal static Trace DeserializeTrace(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string message = default; + DocumentType documentType = default; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("Message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Trace(documentType, documentStreamIds ?? new ChangeTrackingList(), properties ?? new ChangeTrackingList(), serializedAdditionalRawData, message); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Trace)} does not support writing '{options.Format}' format."); + } + } + + Trace IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTrace(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Trace)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new Trace FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeTrace(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/Trace.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/Trace.cs new file mode 100644 index 000000000000..411e5ec67d06 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/Trace.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Trace document type. + public partial class Trace : DocumentIngress + { + /// Initializes a new instance of . + public Trace() + { + DocumentType = DocumentType.Trace; + } + + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + /// Trace message. + internal Trace(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData, string message) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + Message = message; + } + + /// Trace message. + public string Message { get; set; } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.Serialization.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.Serialization.cs new file mode 100644 index 000000000000..53049088a9b1 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace LiveMetrics +{ + internal partial class UnknownDocumentIngress : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + DocumentIngress IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDocumentIngress(document.RootElement, options); + } + + internal static UnknownDocumentIngress DeserializeUnknownDocumentIngress(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DocumentType documentType = "AutoRest.CSharp.Output.Models.Types.EnumTypeValue"; + IList documentStreamIds = default; + IList properties = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("DocumentType"u8)) + { + documentType = new DocumentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("DocumentStreamIds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + documentStreamIds = array; + continue; + } + if (property.NameEquals("Properties"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(KeyValuePairStringString.DeserializeKeyValuePairStringString(item, options)); + } + properties = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownDocumentIngress(documentType, documentStreamIds ?? new ChangeTrackingList(), properties ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support writing '{options.Format}' format."); + } + } + + DocumentIngress IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDocumentIngress(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DocumentIngress)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownDocumentIngress FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownDocumentIngress(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.cs b/sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.cs new file mode 100644 index 000000000000..6212f92f2bc6 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Generated/UnknownDocumentIngress.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace LiveMetrics +{ + /// Unknown version of DocumentIngress. + internal partial class UnknownDocumentIngress : DocumentIngress + { + /// Initializes a new instance of . + /// Telemetry type. Types not defined in enum will get replaced with a 'Unknown' type. + /// An array of document streaming ids. Each id identifies a flow of documents customized by UX customers. + /// Collection of custom properties. + /// Keeps track of any properties unknown to the library. + internal UnknownDocumentIngress(DocumentType documentType, IList documentStreamIds, IList properties, IDictionary serializedAdditionalRawData) : base(documentType, documentStreamIds, properties, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownDocumentIngress() + { + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/src/LiveMetrics.csproj b/sdk/applicationinsights/LiveMetrics/src/LiveMetrics.csproj new file mode 100644 index 000000000000..17d89db02593 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/LiveMetrics.csproj @@ -0,0 +1,19 @@ + + + This is the LiveMetrics client library for developing .NET applications with rich experience. + Azure SDK Code Generation LiveMetrics for Azure Data Plane + 1.0.0-beta.1 + LiveMetrics + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/sdk/applicationinsights/LiveMetrics/src/Properties/AssemblyInfo.cs b/sdk/applicationinsights/LiveMetrics/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..f3bafe56f482 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/src/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("LiveMetrics.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/sdk/applicationinsights/LiveMetrics/tests/Generated/Samples/Samples_LiveMetricsClient.cs b/sdk/applicationinsights/LiveMetrics/tests/Generated/Samples/Samples_LiveMetricsClient.cs new file mode 100644 index 000000000000..94c8c0332502 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/tests/Generated/Samples/Samples_LiveMetricsClient.cs @@ -0,0 +1,454 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace LiveMetrics.Samples +{ + public partial class Samples_LiveMetricsClient + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new + { + Instance = "server-pc-name", + InvariantVersion = 5, + IsWebApp = false, + MachineName = "SERVER-PC-NAME", + PerformanceCollectionSupported = true, + RoleName = "", + StreamId = "41112328328b4edb9aa777aa6d675186", + Timestamp = "2024-02-01T21:36:32.5717105Z", + Version = "2.21.0-429", + }); + Response response = client.IsSubscribed("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new + { + Instance = "server-pc-name", + InvariantVersion = 5, + IsWebApp = false, + MachineName = "SERVER-PC-NAME", + PerformanceCollectionSupported = true, + RoleName = "", + StreamId = "41112328328b4edb9aa777aa6d675186", + Timestamp = "2024-02-01T21:36:32.5717105Z", + Version = "2.21.0-429", + }); + Response response = await client.IsSubscribedAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo_Convenience() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = client.IsSubscribed("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_IsSubscribed_LiveMetricsClientChecksIfItsDataIsSubscribedTo_Convenience_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = await client.IsSubscribedAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new object[] + { +new +{ +Instance = "server-pc-name", +Metrics = new object[] +{ +new +{ +Name = "\\ApplicationInsights\\Requests/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Request Duration", +Value = 2.266, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Succeeded/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Call Duration", +Value = 0, +Weight = 0, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Exceptions/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ASP.NET Applications(__Total__)\\Requests In Application Queue", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\Memory\\Committed Bytes", +Value = 19902644224, +Weight = 1, +}, +new +{ +Name = "\\Processor(_Total)\\% Processor Time", +Value = 54.738, +Weight = 1, +} +}, +Documents = new object[] +{ +new +{ +DocumentType = "Exception", +ExceptionMessage = "Value cannot be null.\r\nParameter name: This exception has properties", +ExceptionType = "System.ArgumentNullException", +Properties = new object[] +{ +new +{ +key = "UserProp2", +value = "UserPropValue2", +}, +new +{ +key = "DeveloperMode", +value = "true", +}, +new +{ +key = "UserProp1", +value = "UserPropValue1", +} +}, +}, +new +{ +DocumentType = "Request", +Duration = "PT0.0010105S", +Name = "GET Home/blablabla", +Properties = new object[] +{ +new +{ +key = "DeveloperMode", +value = "true", +} +}, +ResponseCode = "404", +Url = "http://40.78.109.134/Home/blablabla", +} +}, +Timestamp = "2024-02-01T21:36:30.5717105Z", +Version = "2.1.0.42", +InvariantVersion = 5, +IsWebApp = false, +MachineName = "SERVER-PC-NAME", +PerformanceCollectionSupported = true, +RoleName = "", +StreamId = "41112328328b4edb9aa777aa6d675186", +} + }); + Response response = client.Publish("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + using RequestContent content = RequestContent.Create(new object[] + { +new +{ +Instance = "server-pc-name", +Metrics = new object[] +{ +new +{ +Name = "\\ApplicationInsights\\Requests/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Request Duration", +Value = 2.266, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Requests Succeeded/Sec", +Value = 0.9989, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Call Duration", +Value = 0, +Weight = 0, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Failed/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Dependency Calls Succeeded/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ApplicationInsights\\Exceptions/Sec", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\ASP.NET Applications(__Total__)\\Requests In Application Queue", +Value = 0, +Weight = 1, +}, +new +{ +Name = "\\Memory\\Committed Bytes", +Value = 19902644224, +Weight = 1, +}, +new +{ +Name = "\\Processor(_Total)\\% Processor Time", +Value = 54.738, +Weight = 1, +} +}, +Documents = new object[] +{ +new +{ +DocumentType = "Exception", +ExceptionMessage = "Value cannot be null.\r\nParameter name: This exception has properties", +ExceptionType = "System.ArgumentNullException", +Properties = new object[] +{ +new +{ +key = "UserProp2", +value = "UserPropValue2", +}, +new +{ +key = "DeveloperMode", +value = "true", +}, +new +{ +key = "UserProp1", +value = "UserPropValue1", +} +}, +}, +new +{ +DocumentType = "Request", +Duration = "PT0.0010105S", +Name = "GET Home/blablabla", +Properties = new object[] +{ +new +{ +key = "DeveloperMode", +value = "true", +} +}, +ResponseCode = "404", +Url = "http://40.78.109.134/Home/blablabla", +} +}, +Timestamp = "2024-02-01T21:36:30.5717105Z", +Version = "2.1.0.42", +InvariantVersion = 5, +IsWebApp = false, +MachineName = "SERVER-PC-NAME", +PerformanceCollectionSupported = true, +RoleName = "", +StreamId = "41112328328b4edb9aa777aa6d675186", +} + }); + Response response = await client.PublishAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("ETag").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("FilterGroups")[0].GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Projection").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("Aggregation").ToString()); + Console.WriteLine(result.GetProperty("Metrics")[0].GetProperty("BackEndAggregation").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("Id").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("TelemetryType").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("FieldName").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Predicate").ToString()); + Console.WriteLine(result.GetProperty("DocumentStreams")[0].GetProperty("DocumentFilterGroups")[0].GetProperty("Filters").GetProperty("Filters")[0].GetProperty("Comparand").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics_Convenience() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = client.Publish("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_LiveMetrics_Publish_LiveMetricsClientPublishesLiveMetrics_Convenience_Async() + { + TokenCredential credential = new DefaultAzureCredential(); + LiveMetricsClient client = new LiveMetricsClient(credential); + + Response response = await client.PublishAsync("4473b98e-c70d-4220-b57c-2984c2a0e5cd"); + } + } +} diff --git a/sdk/applicationinsights/LiveMetrics/tests/LiveMetrics.Tests.csproj b/sdk/applicationinsights/LiveMetrics/tests/LiveMetrics.Tests.csproj new file mode 100644 index 000000000000..56fe204affe9 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/tests/LiveMetrics.Tests.csproj @@ -0,0 +1,19 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/sdk/applicationinsights/LiveMetrics/tsp-location.yaml b/sdk/applicationinsights/LiveMetrics/tsp-location.yaml new file mode 100644 index 000000000000..7bcb1998a820 --- /dev/null +++ b/sdk/applicationinsights/LiveMetrics/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/applicationinsights/ApplicationInsights.LiveMetrics +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/confidentialledger/Azure.Security.CodeTransparency/tsp-location.yaml b/sdk/confidentialledger/Azure.Security.CodeTransparency/tsp-location.yaml index 023add8afa1c..3d37b83216aa 100644 --- a/sdk/confidentialledger/Azure.Security.CodeTransparency/tsp-location.yaml +++ b/sdk/confidentialledger/Azure.Security.CodeTransparency/tsp-location.yaml @@ -1,5 +1,4 @@ -commit: bdb83beae5c03e21a9778c5ba746f1f762831efb -repo: Azure/azure-rest-api-specs directory: specification/confidentialledger/Microsoft.CodeTransparency -additionalDirectories: [] - +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/contosowidgetmanager/Azure.Template.Contoso/tsp-location.yaml b/sdk/contosowidgetmanager/Azure.Template.Contoso/tsp-location.yaml new file mode 100644 index 000000000000..9a14f291dcf7 --- /dev/null +++ b/sdk/contosowidgetmanager/Azure.Template.Contoso/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/contosowidgetmanager/Contoso.WidgetManager +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/databasewatcher/Azure.ResourceManager.DatabaseWatcher/tsp-location.yaml b/sdk/databasewatcher/Azure.ResourceManager.DatabaseWatcher/tsp-location.yaml index 622b565ea84a..9e2596803e44 100644 --- a/sdk/databasewatcher/Azure.ResourceManager.DatabaseWatcher/tsp-location.yaml +++ b/sdk/databasewatcher/Azure.ResourceManager.DatabaseWatcher/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/databasewatcher/DatabaseWatcher.Management -commit: 0e8e3ecd19f7e804b70c6ec2ff5bc406666bff6f +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs index 63b4a4aa490a..4e60b307b759 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/AIVisionFaceModelFactory.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; namespace Azure.AI.Vision.Face @@ -299,239 +300,206 @@ public static FaceIdentificationCandidate FaceIdentificationCandidate(Guid perso /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. /// A new instance for mocking. - public static CreateLivenessSessionContent CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode = default, bool? sendResultsToClient = null, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessSingleModalModel = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) + public static CreateLivenessSessionContent CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode = default, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessModelVersion = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) { return new CreateLivenessSessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, + livenessModelVersion, deviceCorrelationId, authTokenTimeToLiveInSeconds, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// A new instance for mocking. - public static CreateLivenessSessionResult CreateLivenessSessionResult(string sessionId = null, string authToken = null) - { - return new CreateLivenessSessionResult(sessionId, authToken, serializedAdditionalRawData: null); - } - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness session. /// A new instance for mocking. - public static LivenessSession LivenessSession(string id = null, DateTimeOffset createdDateTime = default, DateTimeOffset? sessionStartDateTime = null, bool sessionExpired = default, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null, FaceSessionStatus status = default, LivenessSessionAuditEntry result = null) + public static LivenessSession LivenessSession(string sessionId = null, string authToken = null, OperationState status = default, LivenessModel? modelVersion = null, LivenessSessionResults results = null) { return new LivenessSession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - /// The UTC DateTime that the request was received. - /// The request of this entry. - /// The response of this entry. - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - /// The image ID of the session request. - /// The sha256 hash of the verify-image in the request. - /// A new instance for mocking. - public static LivenessSessionAuditEntry LivenessSessionAuditEntry(long id = default, string sessionId = null, string requestId = null, string clientRequestId = null, DateTimeOffset receivedDateTime = default, AuditRequestInfo request = null, AuditLivenessResponseInfo response = null, string digest = null, string sessionImageId = null, string verifyImageHash = null) + /// Initializes a new instance of . + /// The attempts data of underlying liveness call with the session. + /// A new instance for mocking. + public static LivenessSessionResults LivenessSessionResults(IEnumerable attempts = null) { - return new LivenessSessionAuditEntry( - id, - sessionId, - requestId, - clientRequestId, - receivedDateTime, - request, - response, - digest, - sessionImageId, - verifyImageHash, - serializedAdditionalRawData: null); - } + attempts ??= new List(); - /// Initializes a new instance of . - /// The relative URL and query of the liveness request. - /// The HTTP method of the request (i.e., GET, POST, DELETE). - /// The length of the request body in bytes. - /// The content type of the request. - /// The user agent used to submit the request. - /// A new instance for mocking. - public static AuditRequestInfo AuditRequestInfo(string url = null, string method = null, long? contentLength = null, string contentType = null, string userAgent = null) - { - return new AuditRequestInfo( - url, - method, - contentLength, - contentType, - userAgent, - serializedAdditionalRawData: null); + return new LivenessSessionResults(attempts?.ToList(), serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - /// The HTTP status code returned to the client. - /// The server measured latency for this request in milliseconds. - /// A new instance for mocking. - public static AuditLivenessResponseInfo AuditLivenessResponseInfo(LivenessResponseBody body = null, int statusCode = default, long latencyInMilliseconds = default) + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness call, will be null if there is error. + /// The error of the liveness call, will be null if there is result. + /// A new instance for mocking. + public static LivenessSessionAttempt LivenessSessionAttempt(int attemptId = default, OperationState attemptStatus = default, LivenessResult result = null, LivenessError error = null) { - return new AuditLivenessResponseInfo(body, statusCode, latencyInMilliseconds, serializedAdditionalRawData: null); + return new LivenessSessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData: null); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The liveness classification for the target face. - /// Specific targets used for liveness classification. - /// The model version used for liveness classification. - /// The face verification output. Only available when the request is liveness with verify. - /// Additional Properties. - /// A new instance for mocking. - public static LivenessResponseBody LivenessResponseBody(FaceLivenessDecision? livenessDecision = null, LivenessOutputsTarget target = null, LivenessModel? modelVersionUsed = null, LivenessWithVerifyOutputs verifyResult = null, IReadOnlyDictionary additionalProperties = null) - { - additionalProperties ??= new Dictionary(); - - return new LivenessResponseBody(livenessDecision, target, modelVersionUsed, verifyResult, additionalProperties); - } - - /// Initializes a new instance of . - /// The face region where the liveness classification was made on. - /// The file name which contains the face rectangle where the liveness classification was made on. - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - /// The image type which contains the face rectangle where the liveness classification was made on. - /// A new instance for mocking. - public static LivenessOutputsTarget LivenessOutputsTarget(FaceRectangle faceRectangle = null, string fileName = null, int timeOffsetWithinFile = default, FaceImageType imageType = default) + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// A new instance for mocking. + public static LivenessResult LivenessResult(FaceLivenessDecision? livenessDecision = null, LivenessDecisionTargets targets = null, string digest = null, string sessionImageId = null) { - return new LivenessOutputsTarget(faceRectangle, fileName, timeOffsetWithinFile, imageType, serializedAdditionalRawData: null); + return new LivenessResult(livenessDecision, targets, digest, sessionImageId, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The detail of face for verification. - /// The target face liveness face and comparison image face verification confidence. - /// Whether the target liveness face and comparison image face match. - /// A new instance for mocking. - public static LivenessWithVerifyOutputs LivenessWithVerifyOutputs(LivenessWithVerifyImage verifyImage = null, float matchConfidence = default, bool isIdentical = default) + /// Initializes a new instance of . + /// The target from color image used for liveness classification. + /// A new instance for mocking. + public static LivenessDecisionTargets LivenessDecisionTargets(LivenessColorDecisionTarget color = null) { - return new LivenessWithVerifyOutputs(verifyImage, matchConfidence, isIdentical, serializedAdditionalRawData: null); + return new LivenessDecisionTargets(color, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The face region where the comparison image's classification was made. - /// Quality of face image for recognition. - /// A new instance for mocking. - public static LivenessWithVerifyImage LivenessWithVerifyImage(FaceRectangle faceRectangle = null, QualityForRecognition qualityForRecognition = default) + /// Initializes a new instance of . + /// The face region where the liveness classification was made on. + /// A new instance for mocking. + public static LivenessColorDecisionTarget LivenessColorDecisionTarget(FaceRectangle faceRectangle = null) { - return new LivenessWithVerifyImage(faceRectangle, qualityForRecognition, serializedAdditionalRawData: null); + return new LivenessColorDecisionTarget(faceRectangle, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// A new instance for mocking. - public static LivenessSessionItem LivenessSessionItem(string id = null, DateTimeOffset createdDateTime = default, DateTimeOffset? sessionStartDateTime = null, bool sessionExpired = default, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) + /// Initializes a new instance of . + /// The error code. + /// The error message. + /// Targets used for liveness classification. + /// A new instance for mocking. + public static LivenessError LivenessError(string code = null, string message = null, LivenessDecisionTargets targets = null) { - return new LivenessSessionItem( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, - serializedAdditionalRawData: null); + return new LivenessError(code, message, targets, serializedAdditionalRawData: null); } /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// Whether or not return the verify image hash. + /// Threshold for confidence of the face verification. Please refer to the documentation for more details. https://learn.microsoft.com/legal/cognitive-services/face/characteristics-and-limitations?context=%2Fazure%2Fai-services%2Fcomputer-vision%2Fcontext%2Fcontext#recognition-confidence-score. + /// The image stream for verify. Content-Disposition header field for this part must have filename. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// Whether or not return the verify image hash. - /// Threshold for confidence of the face verification. /// A new instance for mocking. - public static CreateLivenessWithVerifySessionContent CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode = default, bool? sendResultsToClient = null, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessSingleModalModel = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null, bool? returnVerifyImageHash = null, float? verifyConfidenceThreshold = null) + public static CreateLivenessWithVerifySessionContent CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode = default, bool? deviceCorrelationIdSetInClient = null, bool? enableSessionImage = null, LivenessModel? livenessModelVersion = null, bool? returnVerifyImageHash = null, float? verifyConfidenceThreshold = null, Stream verifyImage = null, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null) { return new CreateLivenessWithVerifySessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + livenessModelVersion, returnVerifyImageHash, verifyConfidenceThreshold, + verifyImage, + deviceCorrelationId, + authTokenTimeToLiveInSeconds, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// The detail of face for verification. - /// A new instance for mocking. - public static CreateLivenessWithVerifySessionResult CreateLivenessWithVerifySessionResult(string sessionId = null, string authToken = null, LivenessWithVerifyImage verifyImage = null) - { - return new CreateLivenessWithVerifySessionResult(sessionId, authToken, verifyImage, serializedAdditionalRawData: null); - } - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness with verify session. /// A new instance for mocking. - public static LivenessWithVerifySession LivenessWithVerifySession(string id = null, DateTimeOffset createdDateTime = default, DateTimeOffset? sessionStartDateTime = null, bool sessionExpired = default, string deviceCorrelationId = null, int? authTokenTimeToLiveInSeconds = null, FaceSessionStatus status = default, LivenessSessionAuditEntry result = null) + public static LivenessWithVerifySession LivenessWithVerifySession(string sessionId = null, string authToken = null, OperationState status = default, LivenessModel? modelVersion = null, LivenessWithVerifySessionResults results = null) { return new LivenessWithVerifySession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData: null); } + /// Initializes a new instance of . + /// The references used for face verification. + /// The attempts data of underlying liveness with verify call with the session. + /// A new instance for mocking. + public static LivenessWithVerifySessionResults LivenessWithVerifySessionResults(IEnumerable verifyReferences = null, IEnumerable attempts = null) + { + verifyReferences ??= new List(); + attempts ??= new List(); + + return new LivenessWithVerifySessionResults(verifyReferences?.ToList(), attempts?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The image type which contains the face rectangle where the liveness classification was made on. + /// The face region where the comparison image's classification was made. + /// Quality of face image for recognition. + /// A new instance for mocking. + public static LivenessWithVerifyReference LivenessWithVerifyReference(FaceImageType referenceType = default, FaceRectangle faceRectangle = null, QualityForRecognition qualityForRecognition = default) + { + return new LivenessWithVerifyReference(referenceType, faceRectangle, qualityForRecognition, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness with verify call, will be null if there is error. + /// The error of the liveness with verify call, will be null if there is result. + /// A new instance for mocking. + public static LivenessWithVerifySessionAttempt LivenessWithVerifySessionAttempt(int attemptId = default, OperationState attemptStatus = default, LivenessWithVerifyResult result = null, LivenessError error = null) + { + return new LivenessWithVerifySessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The liveness classification for the target face. + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// The face verification output. Only available when the request is liveness with verify. + /// The sha256 hash of the verify-image in the request. + /// A new instance for mocking. + public static LivenessWithVerifyResult LivenessWithVerifyResult(FaceLivenessDecision? livenessDecision = null, LivenessDecisionTargets targets = null, string digest = null, string sessionImageId = null, LivenessWithVerifyOutputs verifyResult = null, string verifyImageHash = null) + { + return new LivenessWithVerifyResult( + livenessDecision, + targets, + digest, + sessionImageId, + verifyResult, + verifyImageHash, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The target face liveness face and comparison image face verification confidence. + /// Whether the target liveness face and comparison image face match. + /// A new instance for mocking. + public static LivenessWithVerifyOutputs LivenessWithVerifyOutputs(float matchConfidence = default, bool isIdentical = default) + { + return new LivenessWithVerifyOutputs(matchConfidence, isIdentical, serializedAdditionalRawData: null); + } + /// Initializes a new instance of . /// User defined name, maximum length is 128. /// Optional user defined data. Length should not exceed 16K. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.cs deleted file mode 100644 index 3448b284f8e3..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Audit entry for a response in the session. - public partial class AuditLivenessResponseInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - /// The HTTP status code returned to the client. - /// The server measured latency for this request in milliseconds. - /// is null. - internal AuditLivenessResponseInfo(LivenessResponseBody body, int statusCode, long latencyInMilliseconds) - { - Argument.AssertNotNull(body, nameof(body)); - - Body = body; - StatusCode = statusCode; - LatencyInMilliseconds = latencyInMilliseconds; - } - - /// Initializes a new instance of . - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - /// The HTTP status code returned to the client. - /// The server measured latency for this request in milliseconds. - /// Keeps track of any properties unknown to the library. - internal AuditLivenessResponseInfo(LivenessResponseBody body, int statusCode, long latencyInMilliseconds, IDictionary serializedAdditionalRawData) - { - Body = body; - StatusCode = statusCode; - LatencyInMilliseconds = latencyInMilliseconds; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal AuditLivenessResponseInfo() - { - } - - /// The response body. The schema of this field will depend on the request.url and request.method used by the client. - public LivenessResponseBody Body { get; } - /// The HTTP status code returned to the client. - public int StatusCode { get; } - /// The server measured latency for this request in milliseconds. - public long LatencyInMilliseconds { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.cs deleted file mode 100644 index 39356d1eb8f8..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Audit entry for a request in the session. - public partial class AuditRequestInfo - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The relative URL and query of the liveness request. - /// The HTTP method of the request (i.e., GET, POST, DELETE). - /// The content type of the request. - /// , or is null. - internal AuditRequestInfo(string url, string method, string contentType) - { - Argument.AssertNotNull(url, nameof(url)); - Argument.AssertNotNull(method, nameof(method)); - Argument.AssertNotNull(contentType, nameof(contentType)); - - Url = url; - Method = method; - ContentType = contentType; - } - - /// Initializes a new instance of . - /// The relative URL and query of the liveness request. - /// The HTTP method of the request (i.e., GET, POST, DELETE). - /// The length of the request body in bytes. - /// The content type of the request. - /// The user agent used to submit the request. - /// Keeps track of any properties unknown to the library. - internal AuditRequestInfo(string url, string method, long? contentLength, string contentType, string userAgent, IDictionary serializedAdditionalRawData) - { - Url = url; - Method = method; - ContentLength = contentLength; - ContentType = contentType; - UserAgent = userAgent; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal AuditRequestInfo() - { - } - - /// The relative URL and query of the liveness request. - public string Url { get; } - /// The HTTP method of the request (i.e., GET, POST, DELETE). - public string Method { get; } - /// The length of the request body in bytes. - public long? ContentLength { get; } - /// The content type of the request. - public string ContentType { get; } - /// The user agent used to submit the request. - public string UserAgent { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs index a27f25f2a008..6790ac937886 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/AzureAIVisionFaceClientOptions.cs @@ -13,7 +13,7 @@ namespace Azure.AI.Vision.Face /// Client options for Azure.AI.Vision.Face library clients. public partial class AzureAIVisionFaceClientOptions : ClientOptions { - private const ServiceVersion LatestVersion = ServiceVersion.V1_2_Preview_1; + private const ServiceVersion LatestVersion = ServiceVersion.V1_2; /// The version of the service to use. public enum ServiceVersion @@ -22,6 +22,8 @@ public enum ServiceVersion V1_1_Preview_1 = 1, /// Service version "v1.2-preview.1". V1_2_Preview_1 = 2, + /// Service version "v1.2". + V1_2 = 3, } internal string Version { get; } @@ -33,6 +35,7 @@ public AzureAIVisionFaceClientOptions(ServiceVersion version = LatestVersion) { ServiceVersion.V1_1_Preview_1 => "v1.1-preview.1", ServiceVersion.V1_2_Preview_1 => "v1.2-preview.1", + ServiceVersion.V1_2 => "v1.2", _ => throw new NotSupportedException() }; } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs index 4c6879d0bbf9..a7d64fe5bb32 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.Serialization.cs @@ -36,11 +36,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("livenessOperationMode"u8); writer.WriteStringValue(LivenessOperationMode.ToString()); - if (Optional.IsDefined(SendResultsToClient)) - { - writer.WritePropertyName("sendResultsToClient"u8); - writer.WriteBooleanValue(SendResultsToClient.Value); - } if (Optional.IsDefined(DeviceCorrelationIdSetInClient)) { writer.WritePropertyName("deviceCorrelationIdSetInClient"u8); @@ -51,10 +46,10 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("enableSessionImage"u8); writer.WriteBooleanValue(EnableSessionImage.Value); } - if (Optional.IsDefined(LivenessSingleModalModel)) + if (Optional.IsDefined(LivenessModelVersion)) { - writer.WritePropertyName("livenessSingleModalModel"u8); - writer.WriteStringValue(LivenessSingleModalModel.Value.ToString()); + writer.WritePropertyName("livenessModelVersion"u8); + writer.WriteStringValue(LivenessModelVersion.Value.ToString()); } if (Optional.IsDefined(DeviceCorrelationId)) { @@ -104,10 +99,9 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon return null; } LivenessOperationMode livenessOperationMode = default; - bool? sendResultsToClient = default; bool? deviceCorrelationIdSetInClient = default; bool? enableSessionImage = default; - LivenessModel? livenessSingleModalModel = default; + LivenessModel? livenessModelVersion = default; string deviceCorrelationId = default; int? authTokenTimeToLiveInSeconds = default; IDictionary serializedAdditionalRawData = default; @@ -119,15 +113,6 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon livenessOperationMode = new LivenessOperationMode(property.Value.GetString()); continue; } - if (property.NameEquals("sendResultsToClient"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sendResultsToClient = property.Value.GetBoolean(); - continue; - } if (property.NameEquals("deviceCorrelationIdSetInClient"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -146,13 +131,13 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon enableSessionImage = property.Value.GetBoolean(); continue; } - if (property.NameEquals("livenessSingleModalModel"u8)) + if (property.NameEquals("livenessModelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - livenessSingleModalModel = new LivenessModel(property.Value.GetString()); + livenessModelVersion = new LivenessModel(property.Value.GetString()); continue; } if (property.NameEquals("deviceCorrelationId"u8)) @@ -177,10 +162,9 @@ internal static CreateLivenessSessionContent DeserializeCreateLivenessSessionCon serializedAdditionalRawData = rawDataDictionary; return new CreateLivenessSessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, + livenessModelVersion, deviceCorrelationId, authTokenTimeToLiveInSeconds, serializedAdditionalRawData); diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs index 9de38ee841c6..66e9ce0ec227 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionContent.cs @@ -54,20 +54,18 @@ public CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode) /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. /// Keeps track of any properties unknown to the library. - internal CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode, bool? sendResultsToClient, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessSingleModalModel, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) + internal CreateLivenessSessionContent(LivenessOperationMode livenessOperationMode, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessModelVersion, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) { LivenessOperationMode = livenessOperationMode; - SendResultsToClient = sendResultsToClient; DeviceCorrelationIdSetInClient = deviceCorrelationIdSetInClient; EnableSessionImage = enableSessionImage; - LivenessSingleModalModel = livenessSingleModalModel; + LivenessModelVersion = livenessModelVersion; DeviceCorrelationId = deviceCorrelationId; AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; _serializedAdditionalRawData = serializedAdditionalRawData; @@ -80,14 +78,12 @@ internal CreateLivenessSessionContent() /// Type of liveness mode the client should follow. public LivenessOperationMode LivenessOperationMode { get; } - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. - public bool? SendResultsToClient { get; set; } /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. public bool? DeviceCorrelationIdSetInClient { get; set; } /// Whether or not store the session image. public bool? EnableSessionImage { get; set; } /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. - public LivenessModel? LivenessSingleModalModel { get; set; } + public LivenessModel? LivenessModelVersion { get; set; } /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. public string DeviceCorrelationId { get; set; } /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.cs deleted file mode 100644 index cf8e5b8e2c7f..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Response of liveness session creation. - public partial class CreateLivenessSessionResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// or is null. - internal CreateLivenessSessionResult(string sessionId, string authToken) - { - Argument.AssertNotNull(sessionId, nameof(sessionId)); - Argument.AssertNotNull(authToken, nameof(authToken)); - - SessionId = sessionId; - AuthToken = authToken; - } - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// Keeps track of any properties unknown to the library. - internal CreateLivenessSessionResult(string sessionId, string authToken, IDictionary serializedAdditionalRawData) - { - SessionId = sessionId; - AuthToken = authToken; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal CreateLivenessSessionResult() - { - } - - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - public string SessionId { get; } - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - public string AuthToken { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs index 27a9c425fb45..20c081c13629 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.Serialization.cs @@ -8,6 +8,7 @@ using System; using System.ClientModel.Primitives; using System.Collections.Generic; +using System.IO; using System.Text.Json; using Azure.Core; @@ -36,11 +37,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("livenessOperationMode"u8); writer.WriteStringValue(LivenessOperationMode.ToString()); - if (Optional.IsDefined(SendResultsToClient)) - { - writer.WritePropertyName("sendResultsToClient"u8); - writer.WriteBooleanValue(SendResultsToClient.Value); - } if (Optional.IsDefined(DeviceCorrelationIdSetInClient)) { writer.WritePropertyName("deviceCorrelationIdSetInClient"u8); @@ -51,20 +47,10 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("enableSessionImage"u8); writer.WriteBooleanValue(EnableSessionImage.Value); } - if (Optional.IsDefined(LivenessSingleModalModel)) + if (Optional.IsDefined(LivenessModelVersion)) { - writer.WritePropertyName("livenessSingleModalModel"u8); - writer.WriteStringValue(LivenessSingleModalModel.Value.ToString()); - } - if (Optional.IsDefined(DeviceCorrelationId)) - { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); - } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) - { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("livenessModelVersion"u8); + writer.WriteStringValue(LivenessModelVersion.Value.ToString()); } if (Optional.IsDefined(ReturnVerifyImageHash)) { @@ -76,6 +62,25 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("verifyConfidenceThreshold"u8); writer.WriteNumberValue(VerifyConfidenceThreshold.Value); } + writer.WritePropertyName("verifyImage"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(VerifyImage)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(VerifyImage), ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(DeviceCorrelationId)) + { + writer.WritePropertyName("deviceCorrelationId"u8); + writer.WriteStringValue(DeviceCorrelationId); + } + if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) + { + writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); + writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -114,14 +119,14 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness return null; } LivenessOperationMode livenessOperationMode = default; - bool? sendResultsToClient = default; bool? deviceCorrelationIdSetInClient = default; bool? enableSessionImage = default; - LivenessModel? livenessSingleModalModel = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; + LivenessModel? livenessModelVersion = default; bool? returnVerifyImageHash = default; float? verifyConfidenceThreshold = default; + Stream verifyImage = default; + string deviceCorrelationId = default; + int? authTokenTimeToLiveInSeconds = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -131,15 +136,6 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness livenessOperationMode = new LivenessOperationMode(property.Value.GetString()); continue; } - if (property.NameEquals("sendResultsToClient"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sendResultsToClient = property.Value.GetBoolean(); - continue; - } if (property.NameEquals("deviceCorrelationIdSetInClient"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -158,45 +154,50 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness enableSessionImage = property.Value.GetBoolean(); continue; } - if (property.NameEquals("livenessSingleModalModel"u8)) + if (property.NameEquals("livenessModelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - livenessSingleModalModel = new LivenessModel(property.Value.GetString()); - continue; - } - if (property.NameEquals("deviceCorrelationId"u8)) - { - deviceCorrelationId = property.Value.GetString(); + livenessModelVersion = new LivenessModel(property.Value.GetString()); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("returnVerifyImageHash"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); + returnVerifyImageHash = property.Value.GetBoolean(); continue; } - if (property.NameEquals("returnVerifyImageHash"u8)) + if (property.NameEquals("verifyConfidenceThreshold"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - returnVerifyImageHash = property.Value.GetBoolean(); + verifyConfidenceThreshold = property.Value.GetSingle(); continue; } - if (property.NameEquals("verifyConfidenceThreshold"u8)) + if (property.NameEquals("verifyImage"u8)) + { + verifyImage = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (property.NameEquals("deviceCorrelationId"u8)) + { + deviceCorrelationId = property.Value.GetString(); + continue; + } + if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - verifyConfidenceThreshold = property.Value.GetSingle(); + authTokenTimeToLiveInSeconds = property.Value.GetInt32(); continue; } if (options.Format != "W") @@ -207,17 +208,68 @@ internal static CreateLivenessWithVerifySessionContent DeserializeCreateLiveness serializedAdditionalRawData = rawDataDictionary; return new CreateLivenessWithVerifySessionContent( livenessOperationMode, - sendResultsToClient, deviceCorrelationIdSetInClient, enableSessionImage, - livenessSingleModalModel, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + livenessModelVersion, returnVerifyImageHash, verifyConfidenceThreshold, + verifyImage, + deviceCorrelationId, + authTokenTimeToLiveInSeconds, serializedAdditionalRawData); } + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(LivenessOperationMode.ToString(), "livenessOperationMode"); + if (Optional.IsDefined(DeviceCorrelationIdSetInClient)) + { + content.Add(DeviceCorrelationIdSetInClient.Value, "deviceCorrelationIdSetInClient"); + } + if (Optional.IsDefined(EnableSessionImage)) + { + content.Add(EnableSessionImage.Value, "enableSessionImage"); + } + if (Optional.IsDefined(LivenessModelVersion)) + { + content.Add(LivenessModelVersion.Value.ToString(), "livenessModelVersion"); + } + if (Optional.IsDefined(ReturnVerifyImageHash)) + { + content.Add(ReturnVerifyImageHash.Value, "returnVerifyImageHash"); + } + if (Optional.IsDefined(VerifyConfidenceThreshold)) + { + content.Add(VerifyConfidenceThreshold.Value, "verifyConfidenceThreshold"); + } + content.Add(VerifyImage, "verifyImage", "verifyImage", "application/octet-stream"); + if (Optional.IsDefined(DeviceCorrelationId)) + { + content.Add(DeviceCorrelationId, "deviceCorrelationId"); + } + if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) + { + content.Add(AuthTokenTimeToLiveInSeconds.Value, "authTokenTimeToLiveInSeconds"); + } + return content; + } + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; @@ -226,6 +278,8 @@ BinaryData IPersistableModel.Write(Model { case "J": return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); default: throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionContent)} does not support writing '{options.Format}' format."); } @@ -247,7 +301,7 @@ CreateLivenessWithVerifySessionContent IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs index 99e890eaf7e3..b0ce40c829f3 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionContent.cs @@ -7,10 +7,11 @@ using System; using System.Collections.Generic; +using System.IO; namespace Azure.AI.Vision.Face { - /// Request for creating liveness with verify session. + /// Request of liveness with verify session creation. public partial class CreateLivenessWithVerifySessionContent { /// @@ -47,33 +48,38 @@ public partial class CreateLivenessWithVerifySessionContent /// Initializes a new instance of . /// Type of liveness mode the client should follow. - public CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode) + /// The image stream for verify. Content-Disposition header field for this part must have filename. + /// is null. + public CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode, Stream verifyImage) { + Argument.AssertNotNull(verifyImage, nameof(verifyImage)); + LivenessOperationMode = livenessOperationMode; + VerifyImage = verifyImage; } /// Initializes a new instance of . /// Type of liveness mode the client should follow. - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. /// Whether or not store the session image. - /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// Whether or not return the verify image hash. + /// Threshold for confidence of the face verification. Please refer to the documentation for more details. https://learn.microsoft.com/legal/cognitive-services/face/characteristics-and-limitations?context=%2Fazure%2Fai-services%2Fcomputer-vision%2Fcontext%2Fcontext#recognition-confidence-score. + /// The image stream for verify. Content-Disposition header field for this part must have filename. /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// Whether or not return the verify image hash. - /// Threshold for confidence of the face verification. /// Keeps track of any properties unknown to the library. - internal CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode, bool? sendResultsToClient, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessSingleModalModel, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, bool? returnVerifyImageHash, float? verifyConfidenceThreshold, IDictionary serializedAdditionalRawData) + internal CreateLivenessWithVerifySessionContent(LivenessOperationMode livenessOperationMode, bool? deviceCorrelationIdSetInClient, bool? enableSessionImage, LivenessModel? livenessModelVersion, bool? returnVerifyImageHash, float? verifyConfidenceThreshold, Stream verifyImage, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) { LivenessOperationMode = livenessOperationMode; - SendResultsToClient = sendResultsToClient; DeviceCorrelationIdSetInClient = deviceCorrelationIdSetInClient; EnableSessionImage = enableSessionImage; - LivenessSingleModalModel = livenessSingleModalModel; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; + LivenessModelVersion = livenessModelVersion; ReturnVerifyImageHash = returnVerifyImageHash; VerifyConfidenceThreshold = verifyConfidenceThreshold; + VerifyImage = verifyImage; + DeviceCorrelationId = deviceCorrelationId; + AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -84,21 +90,21 @@ internal CreateLivenessWithVerifySessionContent() /// Type of liveness mode the client should follow. public LivenessOperationMode LivenessOperationMode { get; } - /// Whether or not to allow a '200 - Success' response body to be sent to the client, which may be undesirable for security reasons. Default is false, clients will receive a '204 - NoContent' empty body response. Regardless of selection, calling Session GetResult will always contain a response body enabling business logic to be implemented. - public bool? SendResultsToClient { get; set; } /// Whether or not to allow client to set their own 'deviceCorrelationId' via the Vision SDK. Default is false, and 'deviceCorrelationId' must be set in this request body. public bool? DeviceCorrelationIdSetInClient { get; set; } /// Whether or not store the session image. public bool? EnableSessionImage { get; set; } /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. - public LivenessModel? LivenessSingleModalModel { get; set; } + public LivenessModel? LivenessModelVersion { get; set; } + /// Whether or not return the verify image hash. + public bool? ReturnVerifyImageHash { get; set; } + /// Threshold for confidence of the face verification. Please refer to the documentation for more details. https://learn.microsoft.com/legal/cognitive-services/face/characteristics-and-limitations?context=%2Fazure%2Fai-services%2Fcomputer-vision%2Fcontext%2Fcontext#recognition-confidence-score. + public float? VerifyConfidenceThreshold { get; set; } + /// The image stream for verify. Content-Disposition header field for this part must have filename. + public Stream VerifyImage { get; } /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. public string DeviceCorrelationId { get; set; } /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. public int? AuthTokenTimeToLiveInSeconds { get; set; } - /// Whether or not return the verify image hash. - public bool? ReturnVerifyImageHash { get; set; } - /// Threshold for confidence of the face verification. - public float? VerifyConfidenceThreshold { get; set; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.cs deleted file mode 100644 index b969512f54ce..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Response of liveness session with verify creation with verify image provided. - public partial class CreateLivenessWithVerifySessionResult - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// or is null. - internal CreateLivenessWithVerifySessionResult(string sessionId, string authToken) - { - Argument.AssertNotNull(sessionId, nameof(sessionId)); - Argument.AssertNotNull(authToken, nameof(authToken)); - - SessionId = sessionId; - AuthToken = authToken; - } - - /// Initializes a new instance of . - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - /// The detail of face for verification. - /// Keeps track of any properties unknown to the library. - internal CreateLivenessWithVerifySessionResult(string sessionId, string authToken, LivenessWithVerifyImage verifyImage, IDictionary serializedAdditionalRawData) - { - SessionId = sessionId; - AuthToken = authToken; - VerifyImage = verifyImage; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal CreateLivenessWithVerifySessionResult() - { - } - - /// The unique session ID of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding Session DELETE operation. - public string SessionId { get; } - /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. - public string AuthToken { get; } - /// The detail of face for verification. - public LivenessWithVerifyImage VerifyImage { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml b/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml index 3754a0217479..8103910b8ae4 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/Docs/FaceSessionClient.xml @@ -11,12 +11,11 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; -Response response = await client.CreateLivenessSessionAsync(body); +Response response = await client.CreateLivenessSessionAsync(body); ]]> @@ -29,12 +28,11 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; -Response response = client.CreateLivenessSession(body); +Response response = client.CreateLivenessSession(body); ]]> @@ -48,8 +46,7 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -58,6 +55,9 @@ Response response = await client.CreateLivenessSessionAsync(content); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -71,8 +71,7 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -81,6 +80,9 @@ Response response = client.CreateLivenessSession(content); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -142,10 +144,11 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = await client.GetLivenessSessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -159,136 +162,85 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = client.GetLivenessSessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> - - -This sample shows how to call GetLivenessSessionsAsync. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = await client.GetLivenessSessionsAsync(); -]]> - - - -This sample shows how to call GetLivenessSessions. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = client.GetLivenessSessions(); -]]> - - - -This sample shows how to call GetLivenessSessionsAsync and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = await client.GetLivenessSessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - - -This sample shows how to call GetLivenessSessions and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = client.GetLivenessSessions("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - + -This sample shows how to call GetLivenessSessionAuditEntriesAsync. +This sample shows how to call CreateLivenessWithVerifySessionAsync. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response> response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); +CreateLivenessWithVerifySessionContent body = null; +Response response = await client.CreateLivenessWithVerifySessionAsync(body); ]]> - + -This sample shows how to call GetLivenessSessionAuditEntries. +This sample shows how to call CreateLivenessWithVerifySession. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response> response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); +CreateLivenessWithVerifySessionContent body = null; +Response response = client.CreateLivenessWithVerifySession(body); ]]> - + -This sample shows how to call GetLivenessSessionAuditEntriesAsync and parse the result. +This sample shows how to call CreateLivenessWithVerifySessionAsync and parse the result. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); +using RequestContent content = null; +Response response = await client.CreateLivenessWithVerifySessionAsync(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> - + -This sample shows how to call GetLivenessSessionAuditEntries and parse the result. +This sample shows how to call CreateLivenessWithVerifySession and parse the result. "); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); -Response response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); +using RequestContent content = null; +Response response = client.CreateLivenessWithVerifySession(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -350,10 +302,17 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = await client.GetLivenessWithVerifySessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> @@ -367,136 +326,17 @@ FaceSessionClient client = new FaceSessionClient(endpoint, credential); Response response = client.GetLivenessWithVerifySessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result.GetProperty("id").ToString()); -Console.WriteLine(result.GetProperty("createdDateTime").ToString()); -Console.WriteLine(result.GetProperty("sessionExpired").ToString()); +Console.WriteLine(result.GetProperty("sessionId").ToString()); +Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionsAsync. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = await client.GetLivenessWithVerifySessionsAsync(); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessions. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = client.GetLivenessWithVerifySessions(); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionsAsync and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = await client.GetLivenessWithVerifySessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessions and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = client.GetLivenessWithVerifySessions("00000000-0000-0000-0000-000000000000", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntriesAsync. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntries. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response> response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntriesAsync and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); -]]> - - - -This sample shows how to call GetLivenessWithVerifySessionAuditEntries and parse the result. -"); -AzureKeyCredential credential = new AzureKeyCredential(""); -FaceSessionClient client = new FaceSessionClient(endpoint, credential); - -Response response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - -JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; -Console.WriteLine(result[0].GetProperty("id").ToString()); -Console.WriteLine(result[0].GetProperty("sessionId").ToString()); -Console.WriteLine(result[0].GetProperty("requestId").ToString()); -Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); -Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); -Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); -Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); -Console.WriteLine(result[0].GetProperty("digest").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); +Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); ]]> diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs index c3695cc5455d..2d54e4f2d175 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionClient.cs @@ -108,14 +108,14 @@ public FaceSessionClient(Uri endpoint, TokenCredential credential, AzureAIVision /// is null. /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-session for more details. /// - public virtual async Task> CreateLivenessSessionAsync(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) + public virtual async Task> CreateLivenessSessionAsync(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) { Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); Response response = await CreateLivenessSessionAsync(content, context).ConfigureAwait(false); - return Response.FromValue(CreateLivenessSessionResult.FromResponse(response), response); + return Response.FromValue(LivenessSession.FromResponse(response), response); } /// Create a new detect liveness session. @@ -124,14 +124,14 @@ public virtual async Task> CreateLivenessS /// is null. /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-session for more details. /// - public virtual Response CreateLivenessSession(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) + public virtual Response CreateLivenessSession(CreateLivenessSessionContent body, CancellationToken cancellationToken = default) { Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); Response response = CreateLivenessSession(content, context); - return Response.FromValue(CreateLivenessSessionResult.FromResponse(response), response); + return Response.FromValue(LivenessSession.FromResponse(response), response); } /// @@ -336,555 +336,15 @@ public virtual Response GetLivenessSessionResult(string session /// Service returned a non-success status code. /// The response returned from the service. /// - public virtual async Task GetLivenessSessionResultAsync(string sessionId, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-result for more details. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual Response GetLivenessSessionResult(string sessionId, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Lists sessions for /detectLiveness/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-sessions for more details. - /// - public virtual async Task>> GetLivenessSessionsAsync(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessSessionsAsync(start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// Lists sessions for /detectLiveness/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-sessions for more details. - /// - public virtual Response> GetLivenessSessions(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessSessions(start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// - /// [Protocol Method] Lists sessions for /detectLiveness/SingleModal. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual async Task GetLivenessSessionsAsync(string start, int? top, RequestContext context) - { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessions"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionsRequest(start, top, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Lists sessions for /detectLiveness/SingleModal. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual Response GetLivenessSessions(string start, int? top, RequestContext context) - { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessions"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionsRequest(start, top, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual async Task>> GetLivenessSessionAuditEntriesAsync(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessSessionAuditEntriesAsync(sessionId, start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual Response> GetLivenessSessionAuditEntries(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessSessionAuditEntries(sessionId, start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual async Task GetLivenessSessionAuditEntriesAsync(string sessionId, string start, int? top, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionAuditEntries"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionAuditEntriesRequest(sessionId, start, top, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-audit-entries for more details. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual Response GetLivenessSessionAuditEntries(string sessionId, string start, int? top, RequestContext context) - { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionAuditEntries"); - scope.Start(); - try - { - using HttpMessage message = CreateGetLivenessSessionAuditEntriesRequest(sessionId, start, top, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// Body parameter. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session for more details. - internal virtual async Task> CreateLivenessWithVerifySessionAsync(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using RequestContent content = body.ToRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateLivenessWithVerifySessionAsync(content, context).ConfigureAwait(false); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// Body parameter. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session for more details. - internal virtual Response CreateLivenessWithVerifySession(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using RequestContent content = body.ToRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateLivenessWithVerifySession(content, context); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The content to send as the body of the request. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual async Task CreateLivenessWithVerifySessionAsync(RequestContent content, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Client device submits VerifyImage during the /detectLivenessWithVerify/singleModal call. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The content to send as the body of the request. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual Response CreateLivenessWithVerifySession(RequestContent content, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// Create a new liveness session with verify. Provide the verify image during session creation. - /// Request content of liveness with verify session creation. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. - internal virtual async Task> CreateLivenessWithVerifySessionWithVerifyImageAsync(CreateLivenessWithVerifySessionMultipartContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateLivenessWithVerifySessionWithVerifyImageAsync(content, content.ContentType, context).ConfigureAwait(false); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// Create a new liveness session with verify. Provide the verify image during session creation. - /// Request content of liveness with verify session creation. - /// The cancellation token to use. - /// is null. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. - internal virtual Response CreateLivenessWithVerifySessionWithVerifyImage(CreateLivenessWithVerifySessionMultipartContent body, CancellationToken cancellationToken = default) - { - Argument.AssertNotNull(body, nameof(body)); - - using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateLivenessWithVerifySessionWithVerifyImage(content, content.ContentType, context); - return Response.FromValue(CreateLivenessWithVerifySessionResult.FromResponse(response), response); - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The content to send as the body of the request. - /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual async Task CreateLivenessWithVerifySessionWithVerifyImageAsync(RequestContent content, string contentType, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySessionWithVerifyImage"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionWithVerifyImageRequest(content, contentType, context); - return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - /// - /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// - /// - /// - /// The content to send as the body of the request. - /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// Service returned a non-success status code. - /// The response returned from the service. - internal virtual Response CreateLivenessWithVerifySessionWithVerifyImage(RequestContent content, string contentType, RequestContext context = null) - { - Argument.AssertNotNull(content, nameof(content)); - - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySessionWithVerifyImage"); - scope.Start(); - try - { - using HttpMessage message = CreateCreateLivenessWithVerifySessionWithVerifyImageRequest(content, contentType, context); - return _pipeline.ProcessMessage(message, context); - } - catch (Exception e) - { - scope.Failed(e); - throw; - } - } - - // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method - /// - /// [Protocol Method] Delete all session related information for matching the specified session id. - /// - /// - /// - /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. - /// - /// - /// - /// - /// The unique ID to reference this session. - /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// Service returned a non-success status code. - /// The response returned from the service. - /// - public virtual async Task DeleteLivenessWithVerifySessionAsync(string sessionId, RequestContext context = null) + public virtual async Task GetLivenessSessionResultAsync(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); scope.Start(); try { - using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); + using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -894,15 +354,19 @@ public virtual async Task DeleteLivenessWithVerifySessionAsync(string } } - // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method /// - /// [Protocol Method] Delete all session related information for matching the specified session id. + /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-session-result for more details. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// /// /// /// The unique ID to reference this session. @@ -911,16 +375,16 @@ public virtual async Task DeleteLivenessWithVerifySessionAsync(string /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual Response DeleteLivenessWithVerifySession(string sessionId, RequestContext context = null) + /// + public virtual Response GetLivenessSessionResult(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessSessionResult"); scope.Start(); try { - using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); + using HttpMessage message = CreateGetLivenessSessionResultRequest(sessionId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -930,38 +394,40 @@ public virtual Response DeleteLivenessWithVerifySession(string sessionId, Reques } } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. - /// The unique ID to reference this session. + /// Create a new liveness session with verify. Provide the verify image during session creation. + /// Request content of liveness with verify session creation. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual async Task> GetLivenessWithVerifySessionResultAsync(string sessionId, CancellationToken cancellationToken = default) + /// is null. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. + /// + public virtual async Task> CreateLivenessWithVerifySessionAsync(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(body, nameof(body)); + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessWithVerifySessionResultAsync(sessionId, context).ConfigureAwait(false); + Response response = await CreateLivenessWithVerifySessionAsync(content, content.ContentType, context).ConfigureAwait(false); return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. - /// The unique ID to reference this session. + /// Create a new liveness session with verify. Provide the verify image during session creation. + /// Request content of liveness with verify session creation. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - /// - public virtual Response GetLivenessWithVerifySessionResult(string sessionId, CancellationToken cancellationToken = default) + /// is null. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/create-liveness-with-verify-session-with-verify-image for more details. + /// + public virtual Response CreateLivenessWithVerifySession(CreateLivenessWithVerifySessionContent body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(body, nameof(body)); + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessWithVerifySessionResult(sessionId, context); + Response response = CreateLivenessWithVerifySession(content, content.ContentType, context); return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. + /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. /// /// /// @@ -970,27 +436,27 @@ public virtual Response GetLivenessWithVerifySessionR /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The unique ID to reference this session. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual async Task GetLivenessWithVerifySessionResultAsync(string sessionId, RequestContext context) + /// + public virtual async Task CreateLivenessWithVerifySessionAsync(RequestContent content, string contentType, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); + using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, contentType, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1001,7 +467,7 @@ public virtual async Task GetLivenessWithVerifySessionResultAsync(stri } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. + /// [Protocol Method] Create a new liveness session with verify. Provide the verify image during session creation. /// /// /// @@ -1010,27 +476,27 @@ public virtual async Task GetLivenessWithVerifySessionResultAsync(stri /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The unique ID to reference this session. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual Response GetLivenessWithVerifySessionResult(string sessionId, RequestContext context) + /// + public virtual Response CreateLivenessWithVerifySession(RequestContent content, string contentType, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.CreateLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); + using HttpMessage message = CreateCreateLivenessWithVerifySessionRequest(content, contentType, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1040,76 +506,33 @@ public virtual Response GetLivenessWithVerifySessionResult(string sessionId, Req } } - /// Lists sessions for /detectLivenessWithVerify/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-sessions for more details. - /// - public virtual async Task>> GetLivenessWithVerifySessionsAsync(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessWithVerifySessionsAsync(start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - - /// Lists sessions for /detectLivenessWithVerify/SingleModal. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. - /// The cancellation token to use. - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-sessions for more details. - /// - public virtual Response> GetLivenessWithVerifySessions(string start = null, int? top = null, CancellationToken cancellationToken = default) - { - RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessWithVerifySessions(start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionItem.DeserializeLivenessSessionItem(item)); - } - value = array; - return Response.FromValue(value, response); - } - + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method /// - /// [Protocol Method] Lists sessions for /detectLivenessWithVerify/SingleModal. + /// [Protocol Method] Delete all session related information for matching the specified session id. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. + /// The unique ID to reference this session. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual async Task GetLivenessWithVerifySessionsAsync(string start, int? top, RequestContext context) + /// + public virtual async Task DeleteLivenessWithVerifySessionAsync(string sessionId, RequestContext context = null) { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessions"); + Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionsRequest(start, top, context); + using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1119,34 +542,33 @@ public virtual async Task GetLivenessWithVerifySessionsAsync(string st } } + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method /// - /// [Protocol Method] Lists sessions for /detectLivenessWithVerify/SingleModal. + /// [Protocol Method] Delete all session related information for matching the specified session id. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. + /// The unique ID to reference this session. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual Response GetLivenessWithVerifySessions(string start, int? top, RequestContext context) + /// + public virtual Response DeleteLivenessWithVerifySession(string sessionId, RequestContext context = null) { - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessions"); + Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); + + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.DeleteLivenessWithVerifySession"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionsRequest(start, top, context); + using HttpMessage message = CreateDeleteLivenessWithVerifySessionRequest(sessionId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1156,58 +578,38 @@ public virtual Response GetLivenessWithVerifySessions(string start, int? top, Re } } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - /// - public virtual async Task>> GetLivenessWithVerifySessionAuditEntriesAsync(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) + /// + public virtual async Task> GetLivenessWithVerifySessionResultAsync(string sessionId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetLivenessWithVerifySessionAuditEntriesAsync(sessionId, start, top, context).ConfigureAwait(false); - IReadOnlyList value = default; - using var document = await JsonDocument.ParseAsync(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions, cancellationToken).ConfigureAwait(false); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); + Response response = await GetLivenessWithVerifySessionResultAsync(sessionId, context).ConfigureAwait(false); + return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } - /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - /// - public virtual Response> GetLivenessWithVerifySessionAuditEntries(string sessionId, string start = null, int? top = null, CancellationToken cancellationToken = default) + /// + public virtual Response GetLivenessWithVerifySessionResult(string sessionId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetLivenessWithVerifySessionAuditEntries(sessionId, start, top, context); - IReadOnlyList value = default; - using var document = JsonDocument.Parse(response.ContentStream, ModelSerializationExtensions.JsonDocumentOptions); - List array = new List(); - foreach (var item in document.RootElement.EnumerateArray()) - { - array.Add(LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(item)); - } - value = array; - return Response.FromValue(value, response); + Response response = GetLivenessWithVerifySessionResult(sessionId, context); + return Response.FromValue(LivenessWithVerifySession.FromResponse(response), response); } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// /// /// @@ -1216,29 +618,27 @@ public virtual Response> GetLivenessWit /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual async Task GetLivenessWithVerifySessionAuditEntriesAsync(string sessionId, string start, int? top, RequestContext context) + /// + public virtual async Task GetLivenessWithVerifySessionResultAsync(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionAuditEntries"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionAuditEntriesRequest(sessionId, start, top, context); + using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1249,7 +649,7 @@ public virtual async Task GetLivenessWithVerifySessionAuditEntriesAsyn } /// - /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-audit-entries for more details. + /// [Protocol Method] Please refer to https://learn.microsoft.com/rest/api/face/liveness-session-operations/get-liveness-with-verify-session-result for more details. /// /// /// @@ -1258,29 +658,27 @@ public virtual async Task GetLivenessWithVerifySessionAuditEntriesAsyn /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// /// The unique ID to reference this session. - /// List resources greater than the "start". It contains no more than 64 characters. Default is empty. - /// The number of items to list, ranging in [1, 1000]. Default is 1000. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - /// - public virtual Response GetLivenessWithVerifySessionAuditEntries(string sessionId, string start, int? top, RequestContext context) + /// + public virtual Response GetLivenessWithVerifySessionResult(string sessionId, RequestContext context) { Argument.AssertNotNullOrEmpty(sessionId, nameof(sessionId)); - using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionAuditEntries"); + using var scope = ClientDiagnostics.CreateScope("FaceSessionClient.GetLivenessWithVerifySessionResult"); scope.Start(); try { - using HttpMessage message = CreateGetLivenessWithVerifySessionAuditEntriesRequest(sessionId, start, top, context); + using HttpMessage message = CreateGetLivenessWithVerifySessionResultRequest(sessionId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1563,7 +961,7 @@ internal HttpMessage CreateCreateLivenessSessionRequest(RequestContent content, uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions", false); + uri.AppendPath("/detectLiveness-sessions", false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); @@ -1573,14 +971,14 @@ internal HttpMessage CreateCreateLivenessSessionRequest(RequestContent content, internal HttpMessage CreateDeleteLivenessSessionRequest(string sessionId, RequestContext context) { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var message = _pipeline.CreateMessage(context, ResponseClassifier204); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions/", false); + uri.AppendPath("/detectLiveness-sessions/", false); uri.AppendPath(sessionId, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); @@ -1596,79 +994,14 @@ internal HttpMessage CreateGetLivenessSessionResultRequest(string sessionId, Req uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions/", false); - uri.AppendPath(sessionId, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessSessionsRequest(string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessSessionAuditEntriesRequest(string sessionId, string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLiveness/singleModal/sessions/", false); + uri.AppendPath("/detectLiveness-sessions/", false); uri.AppendPath(sessionId, true); - uri.AppendPath("/audit", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateCreateLivenessWithVerifySessionRequest(RequestContent content, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Post; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions", false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); - request.Headers.Add("Content-Type", "application/json"); - request.Content = content; return message; } - internal HttpMessage CreateCreateLivenessWithVerifySessionWithVerifyImageRequest(RequestContent content, string contentType, RequestContext context) + internal HttpMessage CreateCreateLivenessWithVerifySessionRequest(RequestContent content, string contentType, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; @@ -1677,7 +1010,7 @@ internal HttpMessage CreateCreateLivenessWithVerifySessionWithVerifyImageRequest uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions", false); + uri.AppendPath("/detectLivenessWithVerify-sessions", false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", contentType); @@ -1687,14 +1020,14 @@ internal HttpMessage CreateCreateLivenessWithVerifySessionWithVerifyImageRequest internal HttpMessage CreateDeleteLivenessWithVerifySessionRequest(string sessionId, RequestContext context) { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var message = _pipeline.CreateMessage(context, ResponseClassifier204); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions/", false); + uri.AppendPath("/detectLivenessWithVerify-sessions/", false); uri.AppendPath(sessionId, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); @@ -1710,56 +1043,8 @@ internal HttpMessage CreateGetLivenessWithVerifySessionResultRequest(string sess uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions/", false); - uri.AppendPath(sessionId, true); - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessWithVerifySessionsRequest(string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } - request.Uri = uri; - request.Headers.Add("Accept", "application/json"); - return message; - } - - internal HttpMessage CreateGetLivenessWithVerifySessionAuditEntriesRequest(string sessionId, string start, int? top, RequestContext context) - { - var message = _pipeline.CreateMessage(context, ResponseClassifier200); - var request = message.Request; - request.Method = RequestMethod.Get; - var uri = new RawRequestUriBuilder(); - uri.Reset(_endpoint); - uri.AppendRaw("/face/", false); - uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/detectLivenessWithVerify/singleModal/sessions/", false); + uri.AppendPath("/detectLivenessWithVerify-sessions/", false); uri.AppendPath(sessionId, true); - uri.AppendPath("/audit", false); - if (start != null) - { - uri.AppendQuery("start", start, true); - } - if (top != null) - { - uri.AppendQuery("top", top.Value, true); - } request.Uri = uri; request.Headers.Add("Accept", "application/json"); return message; @@ -1819,7 +1104,7 @@ internal HttpMessage CreateGetSessionImageRequest(string sessionImageId, Request uri.Reset(_endpoint); uri.AppendRaw("/face/", false); uri.AppendRaw(_apiVersion, true); - uri.AppendPath("/session/sessionImages/", false); + uri.AppendPath("/sessionImages/", false); uri.AppendPath(sessionImageId, true); request.Uri = uri; request.Headers.Add("Accept", "application/octet-stream"); @@ -1839,5 +1124,7 @@ internal static RequestContext FromCancellationToken(CancellationToken cancellat private static ResponseClassifier _responseClassifier200; private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionStatus.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionStatus.cs deleted file mode 100644 index 6c583b333353..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/FaceSessionStatus.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.Vision.Face -{ - /// The current status of the session. - public readonly partial struct FaceSessionStatus : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public FaceSessionStatus(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string NotStartedValue = "NotStarted"; - private const string StartedValue = "Started"; - private const string ResultAvailableValue = "ResultAvailable"; - - /// Session has not started. - public static FaceSessionStatus NotStarted { get; } = new FaceSessionStatus(NotStartedValue); - /// Session has started. - public static FaceSessionStatus Started { get; } = new FaceSessionStatus(StartedValue); - /// Session has available result. - public static FaceSessionStatus ResultAvailable { get; } = new FaceSessionStatus(ResultAvailableValue); - /// Determines if two values are the same. - public static bool operator ==(FaceSessionStatus left, FaceSessionStatus right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(FaceSessionStatus left, FaceSessionStatus right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator FaceSessionStatus(string value) => new FaceSessionStatus(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is FaceSessionStatus other && Equals(other); - /// - public bool Equals(FaceSessionStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs index cfbbbbc33e22..89cf1ece8d4f 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargeFaceListClient.cs @@ -49,7 +49,7 @@ protected LargeFaceListClient() /// https://{resource-name}.cognitiveservices.azure.com). /// /// Valid character is letter in lower case or digit or '-' or '_', maximum length is 64. - /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1". + /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1" | "v1.2". internal LargeFaceListClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string largeFaceListId, string apiVersion) { ClientDiagnostics = clientDiagnostics; diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs index e65069cb45e1..76ab2dea7f22 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LargePersonGroupClient.cs @@ -49,7 +49,7 @@ protected LargePersonGroupClient() /// https://{resource-name}.cognitiveservices.azure.com). /// /// ID of the container. - /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1". + /// API Version. Allowed values: "v1.1-preview.1" | "v1.2-preview.1" | "v1.2". internal LargePersonGroupClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, AzureKeyCredential keyCredential, TokenCredential tokenCredential, Uri endpoint, string largePersonGroupId, string apiVersion) { ClientDiagnostics = clientDiagnostics; diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.Serialization.cs new file mode 100644 index 000000000000..f7ba4a27e38d --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessColorDecisionTarget : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("faceRectangle"u8); + writer.WriteObjectValue(FaceRectangle, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessColorDecisionTarget IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessColorDecisionTarget(document.RootElement, options); + } + + internal static LivenessColorDecisionTarget DeserializeLivenessColorDecisionTarget(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FaceRectangle faceRectangle = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("faceRectangle"u8)) + { + faceRectangle = FaceRectangle.DeserializeFaceRectangle(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessColorDecisionTarget(faceRectangle, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support writing '{options.Format}' format."); + } + } + + LivenessColorDecisionTarget IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessColorDecisionTarget(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessColorDecisionTarget)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessColorDecisionTarget FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessColorDecisionTarget(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.cs similarity index 51% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.cs index 4469cf9f8d50..9a04763a6e3d 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessColorDecisionTarget.cs @@ -10,8 +10,8 @@ namespace Azure.AI.Vision.Face { - /// The liveness classification for target face. - public partial class LivenessOutputsTarget + /// The target from color image used for liveness classification. + public partial class LivenessColorDecisionTarget { /// /// Keeps track of any properties unknown to the library. @@ -45,50 +45,31 @@ public partial class LivenessOutputsTarget /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The face region where the liveness classification was made on. - /// The file name which contains the face rectangle where the liveness classification was made on. - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - /// The image type which contains the face rectangle where the liveness classification was made on. - /// or is null. - internal LivenessOutputsTarget(FaceRectangle faceRectangle, string fileName, int timeOffsetWithinFile, FaceImageType imageType) + /// is null. + internal LivenessColorDecisionTarget(FaceRectangle faceRectangle) { Argument.AssertNotNull(faceRectangle, nameof(faceRectangle)); - Argument.AssertNotNull(fileName, nameof(fileName)); FaceRectangle = faceRectangle; - FileName = fileName; - TimeOffsetWithinFile = timeOffsetWithinFile; - ImageType = imageType; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The face region where the liveness classification was made on. - /// The file name which contains the face rectangle where the liveness classification was made on. - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - /// The image type which contains the face rectangle where the liveness classification was made on. /// Keeps track of any properties unknown to the library. - internal LivenessOutputsTarget(FaceRectangle faceRectangle, string fileName, int timeOffsetWithinFile, FaceImageType imageType, IDictionary serializedAdditionalRawData) + internal LivenessColorDecisionTarget(FaceRectangle faceRectangle, IDictionary serializedAdditionalRawData) { FaceRectangle = faceRectangle; - FileName = fileName; - TimeOffsetWithinFile = timeOffsetWithinFile; - ImageType = imageType; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal LivenessOutputsTarget() + /// Initializes a new instance of for deserialization. + internal LivenessColorDecisionTarget() { } /// The face region where the liveness classification was made on. public FaceRectangle FaceRectangle { get; } - /// The file name which contains the face rectangle where the liveness classification was made on. - public string FileName { get; } - /// The time offset within the file of the frame which contains the face rectangle where the liveness classification was made on. - public int TimeOffsetWithinFile { get; } - /// The image type which contains the face rectangle where the liveness classification was made on. - public FaceImageType ImageType { get; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.Serialization.cs new file mode 100644 index 000000000000..20ea28c7a099 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessDecisionTargets : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("color"u8); + writer.WriteObjectValue(Color, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessDecisionTargets IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessDecisionTargets(document.RootElement, options); + } + + internal static LivenessDecisionTargets DeserializeLivenessDecisionTargets(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + LivenessColorDecisionTarget color = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("color"u8)) + { + color = LivenessColorDecisionTarget.DeserializeLivenessColorDecisionTarget(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessDecisionTargets(color, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support writing '{options.Format}' format."); + } + } + + LivenessDecisionTargets IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessDecisionTargets(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessDecisionTargets)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessDecisionTargets FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessDecisionTargets(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.cs new file mode 100644 index 000000000000..8e64b0560f73 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessDecisionTargets.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The targets used for liveness classification. + public partial class LivenessDecisionTargets + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The target from color image used for liveness classification. + /// is null. + internal LivenessDecisionTargets(LivenessColorDecisionTarget color) + { + Argument.AssertNotNull(color, nameof(color)); + + Color = color; + } + + /// Initializes a new instance of . + /// The target from color image used for liveness classification. + /// Keeps track of any properties unknown to the library. + internal LivenessDecisionTargets(LivenessColorDecisionTarget color, IDictionary serializedAdditionalRawData) + { + Color = color; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessDecisionTargets() + { + } + + /// The target from color image used for liveness classification. + public LivenessColorDecisionTarget Color { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.Serialization.cs new file mode 100644 index 000000000000..617f0c01c590 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessError : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessError)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code); + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + writer.WritePropertyName("targets"u8); + writer.WriteObjectValue(Targets, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessError)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessError(document.RootElement, options); + } + + internal static LivenessError DeserializeLivenessError(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string code = default; + string message = default; + LivenessDecisionTargets targets = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code"u8)) + { + code = property.Value.GetString(); + continue; + } + if (property.NameEquals("message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("targets"u8)) + { + targets = LivenessDecisionTargets.DeserializeLivenessDecisionTargets(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessError(code, message, targets, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessError)} does not support writing '{options.Format}' format."); + } + } + + LivenessError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessError(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessError)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessError FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessError(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.cs new file mode 100644 index 000000000000..4b38aa3b7260 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessError.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The error of the liveness classification. + public partial class LivenessError + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The error code. + /// The error message. + /// Targets used for liveness classification. + /// , or is null. + internal LivenessError(string code, string message, LivenessDecisionTargets targets) + { + Argument.AssertNotNull(code, nameof(code)); + Argument.AssertNotNull(message, nameof(message)); + Argument.AssertNotNull(targets, nameof(targets)); + + Code = code; + Message = message; + Targets = targets; + } + + /// Initializes a new instance of . + /// The error code. + /// The error message. + /// Targets used for liveness classification. + /// Keeps track of any properties unknown to the library. + internal LivenessError(string code, string message, LivenessDecisionTargets targets, IDictionary serializedAdditionalRawData) + { + Code = code; + Message = message; + Targets = targets; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessError() + { + } + + /// The error code. + public string Code { get; } + /// The error message. + public string Message { get; } + /// Targets used for liveness classification. + public LivenessDecisionTargets Targets { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs index f5a0af9fc967..8cf63b931713 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessModel.cs @@ -22,13 +22,10 @@ public LivenessModel(string value) _value = value ?? throw new ArgumentNullException(nameof(value)); } - private const string V20221015Preview04Value = "2022-10-15-preview.04"; - private const string V20231220Preview06Value = "2023-12-20-preview.06"; + private const string V20241115Value = "2024-11-15"; - /// 2022-10-15-preview.04. - public static LivenessModel V20221015Preview04 { get; } = new LivenessModel(V20221015Preview04Value); - /// 2023-12-20-preview.06. - public static LivenessModel V20231220Preview06 { get; } = new LivenessModel(V20231220Preview06Value); + /// 2024-11-15. + public static LivenessModel V20241115 { get; } = new LivenessModel(V20241115Value); /// Determines if two values are the same. public static bool operator ==(LivenessModel left, LivenessModel right) => left.Equals(right); /// Determines if two values are not the same. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.Serialization.cs deleted file mode 100644 index 02ee779e066f..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.Serialization.cs +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.Core; - -namespace Azure.AI.Vision.Face -{ - public partial class LivenessResponseBody : IUtf8JsonSerializable, IJsonModel - { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support writing '{format}' format."); - } - - if (Optional.IsDefined(LivenessDecision)) - { - writer.WritePropertyName("livenessDecision"u8); - writer.WriteStringValue(LivenessDecision.Value.ToString()); - } - if (Optional.IsDefined(Target)) - { - writer.WritePropertyName("target"u8); - writer.WriteObjectValue(Target, options); - } - if (Optional.IsDefined(ModelVersionUsed)) - { - writer.WritePropertyName("modelVersionUsed"u8); - writer.WriteStringValue(ModelVersionUsed.Value.ToString()); - } - if (Optional.IsDefined(VerifyResult)) - { - writer.WritePropertyName("verifyResult"u8); - writer.WriteObjectValue(VerifyResult, options); - } - foreach (var item in AdditionalProperties) - { - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - - LivenessResponseBody IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support reading '{format}' format."); - } - - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessResponseBody(document.RootElement, options); - } - - internal static LivenessResponseBody DeserializeLivenessResponseBody(JsonElement element, ModelReaderWriterOptions options = null) - { - options ??= ModelSerializationExtensions.WireOptions; - - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - FaceLivenessDecision? livenessDecision = default; - LivenessOutputsTarget target = default; - LivenessModel? modelVersionUsed = default; - LivenessWithVerifyOutputs verifyResult = default; - IReadOnlyDictionary additionalProperties = default; - Dictionary additionalPropertiesDictionary = new Dictionary(); - foreach (var property in element.EnumerateObject()) - { - if (property.NameEquals("livenessDecision"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - livenessDecision = new FaceLivenessDecision(property.Value.GetString()); - continue; - } - if (property.NameEquals("target"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - target = LivenessOutputsTarget.DeserializeLivenessOutputsTarget(property.Value, options); - continue; - } - if (property.NameEquals("modelVersionUsed"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - modelVersionUsed = new LivenessModel(property.Value.GetString()); - continue; - } - if (property.NameEquals("verifyResult"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - verifyResult = LivenessWithVerifyOutputs.DeserializeLivenessWithVerifyOutputs(property.Value, options); - continue; - } - additionalPropertiesDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); - } - additionalProperties = additionalPropertiesDictionary; - return new LivenessResponseBody(livenessDecision, target, modelVersionUsed, verifyResult, additionalProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support writing '{options.Format}' format."); - } - } - - LivenessResponseBody IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) - { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - - switch (format) - { - case "J": - { - using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessResponseBody(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(LivenessResponseBody)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// Deserializes the model from a raw response. - /// The response to deserialize the model from. - internal static LivenessResponseBody FromResponse(Response response) - { - using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessResponseBody(document.RootElement); - } - - /// Convert into a . - internal virtual RequestContent ToRequestContent() - { - var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); - return content; - } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.cs deleted file mode 100644 index 5d831412b0a9..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResponseBody.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// The response body of detect liveness API call. - public partial class LivenessResponseBody - { - /// Initializes a new instance of . - internal LivenessResponseBody() - { - AdditionalProperties = new ChangeTrackingDictionary(); - } - - /// Initializes a new instance of . - /// The liveness classification for the target face. - /// Specific targets used for liveness classification. - /// The model version used for liveness classification. - /// The face verification output. Only available when the request is liveness with verify. - /// Additional Properties. - internal LivenessResponseBody(FaceLivenessDecision? livenessDecision, LivenessOutputsTarget target, LivenessModel? modelVersionUsed, LivenessWithVerifyOutputs verifyResult, IReadOnlyDictionary additionalProperties) - { - LivenessDecision = livenessDecision; - Target = target; - ModelVersionUsed = modelVersionUsed; - VerifyResult = verifyResult; - AdditionalProperties = additionalProperties; - } - - /// The liveness classification for the target face. - public FaceLivenessDecision? LivenessDecision { get; } - /// Specific targets used for liveness classification. - public LivenessOutputsTarget Target { get; } - /// The model version used for liveness classification. - public LivenessModel? ModelVersionUsed { get; } - /// The face verification output. Only available when the request is liveness with verify. - public LivenessWithVerifyOutputs VerifyResult { get; } - /// - /// Additional Properties - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - public IReadOnlyDictionary AdditionalProperties { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.Serialization.cs new file mode 100644 index 000000000000..6a386a5fd74b --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.Serialization.cs @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessResult)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(LivenessDecision)) + { + writer.WritePropertyName("livenessDecision"u8); + writer.WriteStringValue(LivenessDecision.Value.ToString()); + } + writer.WritePropertyName("targets"u8); + writer.WriteObjectValue(Targets, options); + writer.WritePropertyName("digest"u8); + writer.WriteStringValue(Digest); + if (Optional.IsDefined(SessionImageId)) + { + writer.WritePropertyName("sessionImageId"u8); + writer.WriteStringValue(SessionImageId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessResult(document.RootElement, options); + } + + internal static LivenessResult DeserializeLivenessResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FaceLivenessDecision? livenessDecision = default; + LivenessDecisionTargets targets = default; + string digest = default; + string sessionImageId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("livenessDecision"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + livenessDecision = new FaceLivenessDecision(property.Value.GetString()); + continue; + } + if (property.NameEquals("targets"u8)) + { + targets = LivenessDecisionTargets.DeserializeLivenessDecisionTargets(property.Value, options); + continue; + } + if (property.NameEquals("digest"u8)) + { + digest = property.Value.GetString(); + continue; + } + if (property.NameEquals("sessionImageId"u8)) + { + sessionImageId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessResult(livenessDecision, targets, digest, sessionImageId, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessResult)} does not support writing '{options.Format}' format."); + } + } + + LivenessResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.cs new file mode 100644 index 000000000000..cf20e1fdeca9 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessResult.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness classification. + public partial class LivenessResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// or is null. + internal LivenessResult(LivenessDecisionTargets targets, string digest) + { + Argument.AssertNotNull(targets, nameof(targets)); + Argument.AssertNotNull(digest, nameof(digest)); + + Targets = targets; + Digest = digest; + } + + /// Initializes a new instance of . + /// The liveness classification for the target face. + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// Keeps track of any properties unknown to the library. + internal LivenessResult(FaceLivenessDecision? livenessDecision, LivenessDecisionTargets targets, string digest, string sessionImageId, IDictionary serializedAdditionalRawData) + { + LivenessDecision = livenessDecision; + Targets = targets; + Digest = digest; + SessionImageId = sessionImageId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessResult() + { + } + + /// The liveness classification for the target face. + public FaceLivenessDecision? LivenessDecision { get; } + /// Targets used for liveness classification. + public LivenessDecisionTargets Targets { get; } + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + public string Digest { get; } + /// The image ID of the session request. + public string SessionImageId { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs index 64b251d3ced0..0513d2d422a9 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.Serialization.cs @@ -36,35 +36,20 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit if (options.Format != "W") { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - writer.WritePropertyName("createdDateTime"u8); - writer.WriteStringValue(CreatedDateTime, "O"); - if (Optional.IsDefined(SessionStartDateTime)) - { - writer.WritePropertyName("sessionStartDateTime"u8); - writer.WriteStringValue(SessionStartDateTime.Value, "O"); - } - writer.WritePropertyName("sessionExpired"u8); - writer.WriteBooleanValue(SessionExpired); - if (Optional.IsDefined(DeviceCorrelationId)) - { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); - } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) - { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("sessionId"u8); + writer.WriteStringValue(SessionId); } + writer.WritePropertyName("authToken"u8); + writer.WriteStringValue(AuthToken); writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); - if (Optional.IsDefined(Result)) + if (Optional.IsDefined(ModelVersion)) { - writer.WritePropertyName("result"u8); - writer.WriteObjectValue(Result, options); + writer.WritePropertyName("modelVersion"u8); + writer.WriteStringValue(ModelVersion.Value.ToString()); } + writer.WritePropertyName("results"u8); + writer.WriteObjectValue(Results, options); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -102,68 +87,42 @@ internal static LivenessSession DeserializeLivenessSession(JsonElement element, { return null; } - string id = default; - DateTimeOffset createdDateTime = default; - DateTimeOffset? sessionStartDateTime = default; - bool sessionExpired = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; - FaceSessionStatus status = default; - LivenessSessionAuditEntry result = default; + string sessionId = default; + string authToken = default; + OperationState status = default; + LivenessModel? modelVersion = default; + LivenessSessionResults results = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("sessionId"u8)) { - id = property.Value.GetString(); + sessionId = property.Value.GetString(); continue; } - if (property.NameEquals("createdDateTime"u8)) + if (property.NameEquals("authToken"u8)) { - createdDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("sessionStartDateTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sessionStartDateTime = property.Value.GetDateTimeOffset("O"); + authToken = property.Value.GetString(); continue; } - if (property.NameEquals("sessionExpired"u8)) - { - sessionExpired = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("deviceCorrelationId"u8)) + if (property.NameEquals("status"u8)) { - deviceCorrelationId = property.Value.GetString(); + status = new OperationState(property.Value.GetString()); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("modelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("status"u8)) - { - status = new FaceSessionStatus(property.Value.GetString()); + modelVersion = new LivenessModel(property.Value.GetString()); continue; } - if (property.NameEquals("result"u8)) + if (property.NameEquals("results"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - result = LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(property.Value, options); + results = LivenessSessionResults.DeserializeLivenessSessionResults(property.Value, options); continue; } if (options.Format != "W") @@ -173,14 +132,11 @@ internal static LivenessSession DeserializeLivenessSession(JsonElement element, } serializedAdditionalRawData = rawDataDictionary; return new LivenessSession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData); } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs index bda0898e67ff..7a073ee5cd14 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSession.cs @@ -46,36 +46,34 @@ public partial class LivenessSession private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// DateTime when this session was created. - /// Whether or not the session is expired. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - internal LivenessSession(DateTimeOffset createdDateTime, bool sessionExpired, FaceSessionStatus status) + /// The results of the liveness session. + /// or is null. + internal LivenessSession(string authToken, OperationState status, LivenessSessionResults results) { - CreatedDateTime = createdDateTime; - SessionExpired = sessionExpired; + Argument.AssertNotNull(authToken, nameof(authToken)); + Argument.AssertNotNull(results, nameof(results)); + + AuthToken = authToken; Status = status; + Results = results; } /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness session. /// Keeps track of any properties unknown to the library. - internal LivenessSession(string id, DateTimeOffset createdDateTime, DateTimeOffset? sessionStartDateTime, bool sessionExpired, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, FaceSessionStatus status, LivenessSessionAuditEntry result, IDictionary serializedAdditionalRawData) + internal LivenessSession(string sessionId, string authToken, OperationState status, LivenessModel? modelVersion, LivenessSessionResults results, IDictionary serializedAdditionalRawData) { - Id = id; - CreatedDateTime = createdDateTime; - SessionStartDateTime = sessionStartDateTime; - SessionExpired = sessionExpired; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; + SessionId = sessionId; + AuthToken = authToken; Status = status; - Result = result; + ModelVersion = modelVersion; + Results = results; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -85,20 +83,14 @@ internal LivenessSession() } /// The unique ID to reference this session. - public string Id { get; } - /// DateTime when this session was created. - public DateTimeOffset CreatedDateTime { get; } - /// DateTime when this session was started by the client. - public DateTimeOffset? SessionStartDateTime { get; } - /// Whether or not the session is expired. - public bool SessionExpired { get; } - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - public string DeviceCorrelationId { get; } - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - public int? AuthTokenTimeToLiveInSeconds { get; } + public string SessionId { get; } + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. + public string AuthToken { get; } /// The current status of the session. - public FaceSessionStatus Status { get; } - /// The latest session audit result only populated if status == 'ResultAvailable'. - public LivenessSessionAuditEntry Result { get; } + public OperationState Status { get; } + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + public LivenessModel? ModelVersion { get; } + /// The results of the liveness session. + public LivenessSessionResults Results { get; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.Serialization.cs new file mode 100644 index 000000000000..35f22ed2bb12 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.Serialization.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessSessionAttempt : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("attemptId"u8); + writer.WriteNumberValue(AttemptId); + writer.WritePropertyName("attemptStatus"u8); + writer.WriteStringValue(AttemptStatus.ToString()); + if (Optional.IsDefined(Result)) + { + writer.WritePropertyName("result"u8); + writer.WriteObjectValue(Result, options); + } + if (Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessSessionAttempt IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessSessionAttempt(document.RootElement, options); + } + + internal static LivenessSessionAttempt DeserializeLivenessSessionAttempt(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int attemptId = default; + OperationState attemptStatus = default; + LivenessResult result = default; + LivenessError error = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("attemptId"u8)) + { + attemptId = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("attemptStatus"u8)) + { + attemptStatus = new OperationState(property.Value.GetString()); + continue; + } + if (property.NameEquals("result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + result = LivenessResult.DeserializeLivenessResult(property.Value, options); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = LivenessError.DeserializeLivenessError(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessSessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support writing '{options.Format}' format."); + } + } + + LivenessSessionAttempt IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionAttempt(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessSessionAttempt)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessSessionAttempt FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionAttempt(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.cs new file mode 100644 index 000000000000..0f414f5127d8 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAttempt.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The liveness session attempt. + public partial class LivenessSessionAttempt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + internal LivenessSessionAttempt(int attemptId, OperationState attemptStatus) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + } + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness call, will be null if there is error. + /// The error of the liveness call, will be null if there is result. + /// Keeps track of any properties unknown to the library. + internal LivenessSessionAttempt(int attemptId, OperationState attemptStatus, LivenessResult result, LivenessError error, IDictionary serializedAdditionalRawData) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + Result = result; + Error = error; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessSessionAttempt() + { + } + + /// The attempt ID, start from 1. + public int AttemptId { get; } + /// The status of the attempt. + public OperationState AttemptStatus { get; } + /// The result of the liveness call, will be null if there is error. + public LivenessResult Result { get; } + /// The error of the liveness call, will be null if there is result. + public LivenessError Error { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.cs deleted file mode 100644 index 46b364a13ffd..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.cs +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Audit entry for a request in session. - public partial class LivenessSessionAuditEntry - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - /// The UTC DateTime that the request was received. - /// The request of this entry. - /// The response of this entry. - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - /// , , , , or is null. - internal LivenessSessionAuditEntry(long id, string sessionId, string requestId, string clientRequestId, DateTimeOffset receivedDateTime, AuditRequestInfo request, AuditLivenessResponseInfo response, string digest) - { - Argument.AssertNotNull(sessionId, nameof(sessionId)); - Argument.AssertNotNull(requestId, nameof(requestId)); - Argument.AssertNotNull(clientRequestId, nameof(clientRequestId)); - Argument.AssertNotNull(request, nameof(request)); - Argument.AssertNotNull(response, nameof(response)); - Argument.AssertNotNull(digest, nameof(digest)); - - Id = id; - SessionId = sessionId; - RequestId = requestId; - ClientRequestId = clientRequestId; - ReceivedDateTime = receivedDateTime; - Request = request; - Response = response; - Digest = digest; - } - - /// Initializes a new instance of . - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - /// The UTC DateTime that the request was received. - /// The request of this entry. - /// The response of this entry. - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - /// The image ID of the session request. - /// The sha256 hash of the verify-image in the request. - /// Keeps track of any properties unknown to the library. - internal LivenessSessionAuditEntry(long id, string sessionId, string requestId, string clientRequestId, DateTimeOffset receivedDateTime, AuditRequestInfo request, AuditLivenessResponseInfo response, string digest, string sessionImageId, string verifyImageHash, IDictionary serializedAdditionalRawData) - { - Id = id; - SessionId = sessionId; - RequestId = requestId; - ClientRequestId = clientRequestId; - ReceivedDateTime = receivedDateTime; - Request = request; - Response = response; - Digest = digest; - SessionImageId = sessionImageId; - VerifyImageHash = verifyImageHash; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal LivenessSessionAuditEntry() - { - } - - /// The unique id to refer to this audit request. Use this id with the 'start' query parameter to continue on to the next page of audit results. - public long Id { get; } - /// The unique sessionId of the created session. It will expire 48 hours after it was created or may be deleted sooner using the corresponding session DELETE operation. - public string SessionId { get; } - /// The unique requestId that is returned by the service to the client in the 'apim-request-id' header. - public string RequestId { get; } - /// The unique clientRequestId that is sent by the client in the 'client-request-id' header. - public string ClientRequestId { get; } - /// The UTC DateTime that the request was received. - public DateTimeOffset ReceivedDateTime { get; } - /// The request of this entry. - public AuditRequestInfo Request { get; } - /// The response of this entry. - public AuditLivenessResponseInfo Response { get; } - /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. - public string Digest { get; } - /// The image ID of the session request. - public string SessionImageId { get; } - /// The sha256 hash of the verify-image in the request. - public string VerifyImageHash { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.cs deleted file mode 100644 index e46e4901a8a1..000000000000 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.Vision.Face -{ - /// Session data returned for enumeration. - public partial class LivenessSessionItem - { - /// - /// Keeps track of any properties unknown to the library. - /// - /// To assign an object to the value of this property use . - /// - /// - /// To assign an already formatted json string to this property use . - /// - /// - /// Examples: - /// - /// - /// BinaryData.FromObjectAsJson("foo") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromString("\"foo\"") - /// Creates a payload of "foo". - /// - /// - /// BinaryData.FromObjectAsJson(new { key = "value" }) - /// Creates a payload of { "key": "value" }. - /// - /// - /// BinaryData.FromString("{\"key\": \"value\"}") - /// Creates a payload of { "key": "value" }. - /// - /// - /// - /// - private IDictionary _serializedAdditionalRawData; - - /// Initializes a new instance of . - /// DateTime when this session was created. - /// Whether or not the session is expired. - internal LivenessSessionItem(DateTimeOffset createdDateTime, bool sessionExpired) - { - CreatedDateTime = createdDateTime; - SessionExpired = sessionExpired; - } - - /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - /// Keeps track of any properties unknown to the library. - internal LivenessSessionItem(string id, DateTimeOffset createdDateTime, DateTimeOffset? sessionStartDateTime, bool sessionExpired, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, IDictionary serializedAdditionalRawData) - { - Id = id; - CreatedDateTime = createdDateTime; - SessionStartDateTime = sessionStartDateTime; - SessionExpired = sessionExpired; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; - _serializedAdditionalRawData = serializedAdditionalRawData; - } - - /// Initializes a new instance of for deserialization. - internal LivenessSessionItem() - { - } - - /// The unique ID to reference this session. - public string Id { get; } - /// DateTime when this session was created. - public DateTimeOffset CreatedDateTime { get; } - /// DateTime when this session was started by the client. - public DateTimeOffset? SessionStartDateTime { get; } - /// Whether or not the session is expired. - public bool SessionExpired { get; } - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - public string DeviceCorrelationId { get; } - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - public int? AuthTokenTimeToLiveInSeconds { get; } - } -} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.Serialization.cs new file mode 100644 index 000000000000..75f8162577e8 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessSessionResults : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("attempts"u8); + writer.WriteStartArray(); + foreach (var item in Attempts) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessSessionResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessSessionResults(document.RootElement, options); + } + + internal static LivenessSessionResults DeserializeLivenessSessionResults(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList attempts = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("attempts"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(LivenessSessionAttempt.DeserializeLivenessSessionAttempt(item, options)); + } + attempts = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessSessionResults(attempts, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support writing '{options.Format}' format."); + } + } + + LivenessSessionResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionResults(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessSessionResults)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessSessionResults FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessSessionResults(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.cs new file mode 100644 index 000000000000..1a3686a45577 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionResults.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness session. + public partial class LivenessSessionResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The attempts data of underlying liveness call with the session. + /// is null. + internal LivenessSessionResults(IEnumerable attempts) + { + Argument.AssertNotNull(attempts, nameof(attempts)); + + Attempts = attempts.ToList(); + } + + /// Initializes a new instance of . + /// The attempts data of underlying liveness call with the session. + /// Keeps track of any properties unknown to the library. + internal LivenessSessionResults(IReadOnlyList attempts, IDictionary serializedAdditionalRawData) + { + Attempts = attempts; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessSessionResults() + { + } + + /// The attempts data of underlying liveness call with the session. + public IReadOnlyList Attempts { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs index f82efb60a43d..79f11aaffbd3 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.Serialization.cs @@ -34,8 +34,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit throw new FormatException($"The model {nameof(LivenessWithVerifyOutputs)} does not support writing '{format}' format."); } - writer.WritePropertyName("verifyImage"u8); - writer.WriteObjectValue(VerifyImage, options); writer.WritePropertyName("matchConfidence"u8); writer.WriteNumberValue(MatchConfidence); writer.WritePropertyName("isIdentical"u8); @@ -77,18 +75,12 @@ internal static LivenessWithVerifyOutputs DeserializeLivenessWithVerifyOutputs(J { return null; } - LivenessWithVerifyImage verifyImage = default; float matchConfidence = default; bool isIdentical = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("verifyImage"u8)) - { - verifyImage = LivenessWithVerifyImage.DeserializeLivenessWithVerifyImage(property.Value, options); - continue; - } if (property.NameEquals("matchConfidence"u8)) { matchConfidence = property.Value.GetSingle(); @@ -105,7 +97,7 @@ internal static LivenessWithVerifyOutputs DeserializeLivenessWithVerifyOutputs(J } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessWithVerifyOutputs(verifyImage, matchConfidence, isIdentical, serializedAdditionalRawData); + return new LivenessWithVerifyOutputs(matchConfidence, isIdentical, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs index 45c6d6405b7f..3abf91ab403f 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyOutputs.cs @@ -46,27 +46,20 @@ public partial class LivenessWithVerifyOutputs private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// The detail of face for verification. /// The target face liveness face and comparison image face verification confidence. /// Whether the target liveness face and comparison image face match. - /// is null. - internal LivenessWithVerifyOutputs(LivenessWithVerifyImage verifyImage, float matchConfidence, bool isIdentical) + internal LivenessWithVerifyOutputs(float matchConfidence, bool isIdentical) { - Argument.AssertNotNull(verifyImage, nameof(verifyImage)); - - VerifyImage = verifyImage; MatchConfidence = matchConfidence; IsIdentical = isIdentical; } /// Initializes a new instance of . - /// The detail of face for verification. /// The target face liveness face and comparison image face verification confidence. /// Whether the target liveness face and comparison image face match. /// Keeps track of any properties unknown to the library. - internal LivenessWithVerifyOutputs(LivenessWithVerifyImage verifyImage, float matchConfidence, bool isIdentical, IDictionary serializedAdditionalRawData) + internal LivenessWithVerifyOutputs(float matchConfidence, bool isIdentical, IDictionary serializedAdditionalRawData) { - VerifyImage = verifyImage; MatchConfidence = matchConfidence; IsIdentical = isIdentical; _serializedAdditionalRawData = serializedAdditionalRawData; @@ -77,8 +70,6 @@ internal LivenessWithVerifyOutputs() { } - /// The detail of face for verification. - public LivenessWithVerifyImage VerifyImage { get; } /// The target face liveness face and comparison image face verification confidence. public float MatchConfidence { get; } /// Whether the target liveness face and comparison image face match. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.Serialization.cs similarity index 65% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.Serialization.cs index fa30773e4bc8..dcf2014c1505 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class LivenessWithVerifyImage : IUtf8JsonSerializable, IJsonModel + public partial class LivenessWithVerifyReference : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,12 +28,14 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support writing '{format}' format."); } + writer.WritePropertyName("referenceType"u8); + writer.WriteStringValue(ReferenceType.ToString()); writer.WritePropertyName("faceRectangle"u8); writer.WriteObjectValue(FaceRectangle, options); writer.WritePropertyName("qualityForRecognition"u8); @@ -55,19 +57,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessWithVerifyImage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessWithVerifyReference IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessWithVerifyImage(document.RootElement, options); + return DeserializeLivenessWithVerifyReference(document.RootElement, options); } - internal static LivenessWithVerifyImage DeserializeLivenessWithVerifyImage(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessWithVerifyReference DeserializeLivenessWithVerifyReference(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -75,12 +77,18 @@ internal static LivenessWithVerifyImage DeserializeLivenessWithVerifyImage(JsonE { return null; } + FaceImageType referenceType = default; FaceRectangle faceRectangle = default; QualityForRecognition qualityForRecognition = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { + if (property.NameEquals("referenceType"u8)) + { + referenceType = new FaceImageType(property.Value.GetString()); + continue; + } if (property.NameEquals("faceRectangle"u8)) { faceRectangle = FaceRectangle.DeserializeFaceRectangle(property.Value, options); @@ -97,46 +105,46 @@ internal static LivenessWithVerifyImage DeserializeLivenessWithVerifyImage(JsonE } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessWithVerifyImage(faceRectangle, qualityForRecognition, serializedAdditionalRawData); + return new LivenessWithVerifyReference(referenceType, faceRectangle, qualityForRecognition, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support writing '{options.Format}' format."); } } - LivenessWithVerifyImage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessWithVerifyReference IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessWithVerifyImage(document.RootElement, options); + return DeserializeLivenessWithVerifyReference(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessWithVerifyImage)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyReference)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessWithVerifyImage FromResponse(Response response) + internal static LivenessWithVerifyReference FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessWithVerifyImage(document.RootElement); + return DeserializeLivenessWithVerifyReference(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.cs similarity index 73% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.cs index 2cb09a6725ef..fe5f68bc902c 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyImage.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyReference.cs @@ -11,7 +11,7 @@ namespace Azure.AI.Vision.Face { /// The detail of face for verification. - public partial class LivenessWithVerifyImage + public partial class LivenessWithVerifyReference { /// /// Keeps track of any properties unknown to the library. @@ -45,34 +45,40 @@ public partial class LivenessWithVerifyImage /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The image type which contains the face rectangle where the liveness classification was made on. /// The face region where the comparison image's classification was made. /// Quality of face image for recognition. /// is null. - internal LivenessWithVerifyImage(FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition) + internal LivenessWithVerifyReference(FaceImageType referenceType, FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition) { Argument.AssertNotNull(faceRectangle, nameof(faceRectangle)); + ReferenceType = referenceType; FaceRectangle = faceRectangle; QualityForRecognition = qualityForRecognition; } - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The image type which contains the face rectangle where the liveness classification was made on. /// The face region where the comparison image's classification was made. /// Quality of face image for recognition. /// Keeps track of any properties unknown to the library. - internal LivenessWithVerifyImage(FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition, IDictionary serializedAdditionalRawData) + internal LivenessWithVerifyReference(FaceImageType referenceType, FaceRectangle faceRectangle, QualityForRecognition qualityForRecognition, IDictionary serializedAdditionalRawData) { + ReferenceType = referenceType; FaceRectangle = faceRectangle; QualityForRecognition = qualityForRecognition; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal LivenessWithVerifyImage() + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifyReference() { } + /// The image type which contains the face rectangle where the liveness classification was made on. + public FaceImageType ReferenceType { get; } /// The face region where the comparison image's classification was made. public FaceRectangle FaceRectangle { get; } /// Quality of face image for recognition. diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.Serialization.cs similarity index 55% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.Serialization.cs rename to sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.Serialization.cs index 48df626d12e3..f34e22a4cdbe 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionAuditEntry.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.Vision.Face { - public partial class LivenessSessionAuditEntry : IUtf8JsonSerializable, IJsonModel + public partial class LivenessWithVerifyResult : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,26 +28,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support writing '{format}' format."); } - writer.WritePropertyName("id"u8); - writer.WriteNumberValue(Id); - writer.WritePropertyName("sessionId"u8); - writer.WriteStringValue(SessionId); - writer.WritePropertyName("requestId"u8); - writer.WriteStringValue(RequestId); - writer.WritePropertyName("clientRequestId"u8); - writer.WriteStringValue(ClientRequestId); - writer.WritePropertyName("receivedDateTime"u8); - writer.WriteStringValue(ReceivedDateTime, "O"); - writer.WritePropertyName("request"u8); - writer.WriteObjectValue(Request, options); - writer.WritePropertyName("response"u8); - writer.WriteObjectValue(Response, options); + if (Optional.IsDefined(LivenessDecision)) + { + writer.WritePropertyName("livenessDecision"u8); + writer.WriteStringValue(LivenessDecision.Value.ToString()); + } + writer.WritePropertyName("targets"u8); + writer.WriteObjectValue(Targets, options); writer.WritePropertyName("digest"u8); writer.WriteStringValue(Digest); if (Optional.IsDefined(SessionImageId)) @@ -55,6 +48,11 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("sessionImageId"u8); writer.WriteStringValue(SessionImageId); } + if (Optional.IsDefined(VerifyResult)) + { + writer.WritePropertyName("verifyResult"u8); + writer.WriteObjectValue(VerifyResult, options); + } if (Optional.IsDefined(VerifyImageHash)) { writer.WritePropertyName("verifyImageHash"u8); @@ -77,19 +75,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessSessionAuditEntry IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + LivenessWithVerifyResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessSessionAuditEntry(document.RootElement, options); + return DeserializeLivenessWithVerifyResult(document.RootElement, options); } - internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(JsonElement element, ModelReaderWriterOptions options = null) + internal static LivenessWithVerifyResult DeserializeLivenessWithVerifyResult(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -97,53 +95,28 @@ internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(J { return null; } - long id = default; - string sessionId = default; - string requestId = default; - string clientRequestId = default; - DateTimeOffset receivedDateTime = default; - AuditRequestInfo request = default; - AuditLivenessResponseInfo response = default; + FaceLivenessDecision? livenessDecision = default; + LivenessDecisionTargets targets = default; string digest = default; string sessionImageId = default; + LivenessWithVerifyOutputs verifyResult = default; string verifyImageHash = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) - { - id = property.Value.GetInt64(); - continue; - } - if (property.NameEquals("sessionId"u8)) - { - sessionId = property.Value.GetString(); - continue; - } - if (property.NameEquals("requestId"u8)) - { - requestId = property.Value.GetString(); - continue; - } - if (property.NameEquals("clientRequestId"u8)) + if (property.NameEquals("livenessDecision"u8)) { - clientRequestId = property.Value.GetString(); - continue; - } - if (property.NameEquals("receivedDateTime"u8)) - { - receivedDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("request"u8)) - { - request = AuditRequestInfo.DeserializeAuditRequestInfo(property.Value, options); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + livenessDecision = new FaceLivenessDecision(property.Value.GetString()); continue; } - if (property.NameEquals("response"u8)) + if (property.NameEquals("targets"u8)) { - response = AuditLivenessResponseInfo.DeserializeAuditLivenessResponseInfo(property.Value, options); + targets = LivenessDecisionTargets.DeserializeLivenessDecisionTargets(property.Value, options); continue; } if (property.NameEquals("digest"u8)) @@ -156,6 +129,15 @@ internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(J sessionImageId = property.Value.GetString(); continue; } + if (property.NameEquals("verifyResult"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + verifyResult = LivenessWithVerifyOutputs.DeserializeLivenessWithVerifyOutputs(property.Value, options); + continue; + } if (property.NameEquals("verifyImageHash"u8)) { verifyImageHash = property.Value.GetString(); @@ -167,57 +149,53 @@ internal static LivenessSessionAuditEntry DeserializeLivenessSessionAuditEntry(J } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessSessionAuditEntry( - id, - sessionId, - requestId, - clientRequestId, - receivedDateTime, - request, - response, + return new LivenessWithVerifyResult( + livenessDecision, + targets, digest, sessionImageId, + verifyResult, verifyImageHash, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support writing '{options.Format}' format."); } } - LivenessSessionAuditEntry IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + LivenessWithVerifyResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionAuditEntry(document.RootElement, options); + return DeserializeLivenessWithVerifyResult(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessSessionAuditEntry)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(LivenessWithVerifyResult)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessSessionAuditEntry FromResponse(Response response) + internal static LivenessWithVerifyResult FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionAuditEntry(document.RootElement); + return DeserializeLivenessWithVerifyResult(document.RootElement); } /// Convert into a . diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.cs new file mode 100644 index 000000000000..730d5cac8f3c --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifyResult.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness with verify call. + public partial class LivenessWithVerifyResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// or is null. + internal LivenessWithVerifyResult(LivenessDecisionTargets targets, string digest) + { + Argument.AssertNotNull(targets, nameof(targets)); + Argument.AssertNotNull(digest, nameof(digest)); + + Targets = targets; + Digest = digest; + } + + /// Initializes a new instance of . + /// The liveness classification for the target face. + /// Targets used for liveness classification. + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + /// The image ID of the session request. + /// The face verification output. Only available when the request is liveness with verify. + /// The sha256 hash of the verify-image in the request. + /// Keeps track of any properties unknown to the library. + internal LivenessWithVerifyResult(FaceLivenessDecision? livenessDecision, LivenessDecisionTargets targets, string digest, string sessionImageId, LivenessWithVerifyOutputs verifyResult, string verifyImageHash, IDictionary serializedAdditionalRawData) + { + LivenessDecision = livenessDecision; + Targets = targets; + Digest = digest; + SessionImageId = sessionImageId; + VerifyResult = verifyResult; + VerifyImageHash = verifyImageHash; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifyResult() + { + } + + /// The liveness classification for the target face. + public FaceLivenessDecision? LivenessDecision { get; } + /// Targets used for liveness classification. + public LivenessDecisionTargets Targets { get; } + /// The server calculated digest for this request. If the client reported digest differs from the server calculated digest, then the message integrity between the client and service has been compromised and the result should not be trusted. For more information, see how to guides on how to leverage this value to secure your end-to-end solution. + public string Digest { get; } + /// The image ID of the session request. + public string SessionImageId { get; } + /// The face verification output. Only available when the request is liveness with verify. + public LivenessWithVerifyOutputs VerifyResult { get; } + /// The sha256 hash of the verify-image in the request. + public string VerifyImageHash { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs index d025789726cf..e8db35212e75 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.Serialization.cs @@ -36,35 +36,20 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit if (options.Format != "W") { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - writer.WritePropertyName("createdDateTime"u8); - writer.WriteStringValue(CreatedDateTime, "O"); - if (Optional.IsDefined(SessionStartDateTime)) - { - writer.WritePropertyName("sessionStartDateTime"u8); - writer.WriteStringValue(SessionStartDateTime.Value, "O"); - } - writer.WritePropertyName("sessionExpired"u8); - writer.WriteBooleanValue(SessionExpired); - if (Optional.IsDefined(DeviceCorrelationId)) - { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); - } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) - { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("sessionId"u8); + writer.WriteStringValue(SessionId); } + writer.WritePropertyName("authToken"u8); + writer.WriteStringValue(AuthToken); writer.WritePropertyName("status"u8); writer.WriteStringValue(Status.ToString()); - if (Optional.IsDefined(Result)) + if (Optional.IsDefined(ModelVersion)) { - writer.WritePropertyName("result"u8); - writer.WriteObjectValue(Result, options); + writer.WritePropertyName("modelVersion"u8); + writer.WriteStringValue(ModelVersion.Value.ToString()); } + writer.WritePropertyName("results"u8); + writer.WriteObjectValue(Results, options); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -102,68 +87,42 @@ internal static LivenessWithVerifySession DeserializeLivenessWithVerifySession(J { return null; } - string id = default; - DateTimeOffset createdDateTime = default; - DateTimeOffset? sessionStartDateTime = default; - bool sessionExpired = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; - FaceSessionStatus status = default; - LivenessSessionAuditEntry result = default; + string sessionId = default; + string authToken = default; + OperationState status = default; + LivenessModel? modelVersion = default; + LivenessWithVerifySessionResults results = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("sessionId"u8)) { - id = property.Value.GetString(); + sessionId = property.Value.GetString(); continue; } - if (property.NameEquals("createdDateTime"u8)) + if (property.NameEquals("authToken"u8)) { - createdDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("sessionStartDateTime"u8)) - { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sessionStartDateTime = property.Value.GetDateTimeOffset("O"); + authToken = property.Value.GetString(); continue; } - if (property.NameEquals("sessionExpired"u8)) - { - sessionExpired = property.Value.GetBoolean(); - continue; - } - if (property.NameEquals("deviceCorrelationId"u8)) + if (property.NameEquals("status"u8)) { - deviceCorrelationId = property.Value.GetString(); + status = new OperationState(property.Value.GetString()); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("modelVersion"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("status"u8)) - { - status = new FaceSessionStatus(property.Value.GetString()); + modelVersion = new LivenessModel(property.Value.GetString()); continue; } - if (property.NameEquals("result"u8)) + if (property.NameEquals("results"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - result = LivenessSessionAuditEntry.DeserializeLivenessSessionAuditEntry(property.Value, options); + results = LivenessWithVerifySessionResults.DeserializeLivenessWithVerifySessionResults(property.Value, options); continue; } if (options.Format != "W") @@ -173,14 +132,11 @@ internal static LivenessWithVerifySession DeserializeLivenessWithVerifySession(J } serializedAdditionalRawData = rawDataDictionary; return new LivenessWithVerifySession( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + sessionId, + authToken, status, - result, + modelVersion, + results, serializedAdditionalRawData); } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs index 9aaec1db8d47..5db8b918edbc 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySession.cs @@ -46,36 +46,34 @@ public partial class LivenessWithVerifySession private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// DateTime when this session was created. - /// Whether or not the session is expired. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - internal LivenessWithVerifySession(DateTimeOffset createdDateTime, bool sessionExpired, FaceSessionStatus status) + /// The results of the liveness with verify session. + /// or is null. + internal LivenessWithVerifySession(string authToken, OperationState status, LivenessWithVerifySessionResults results) { - CreatedDateTime = createdDateTime; - SessionExpired = sessionExpired; + Argument.AssertNotNull(authToken, nameof(authToken)); + Argument.AssertNotNull(results, nameof(results)); + + AuthToken = authToken; Status = status; + Results = results; } /// Initializes a new instance of . - /// The unique ID to reference this session. - /// DateTime when this session was created. - /// DateTime when this session was started by the client. - /// Whether or not the session is expired. - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. + /// The unique ID to reference this session. + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. /// The current status of the session. - /// The latest session audit result only populated if status == 'ResultAvailable'. + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + /// The results of the liveness with verify session. /// Keeps track of any properties unknown to the library. - internal LivenessWithVerifySession(string id, DateTimeOffset createdDateTime, DateTimeOffset? sessionStartDateTime, bool sessionExpired, string deviceCorrelationId, int? authTokenTimeToLiveInSeconds, FaceSessionStatus status, LivenessSessionAuditEntry result, IDictionary serializedAdditionalRawData) + internal LivenessWithVerifySession(string sessionId, string authToken, OperationState status, LivenessModel? modelVersion, LivenessWithVerifySessionResults results, IDictionary serializedAdditionalRawData) { - Id = id; - CreatedDateTime = createdDateTime; - SessionStartDateTime = sessionStartDateTime; - SessionExpired = sessionExpired; - DeviceCorrelationId = deviceCorrelationId; - AuthTokenTimeToLiveInSeconds = authTokenTimeToLiveInSeconds; + SessionId = sessionId; + AuthToken = authToken; Status = status; - Result = result; + ModelVersion = modelVersion; + Results = results; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -85,20 +83,14 @@ internal LivenessWithVerifySession() } /// The unique ID to reference this session. - public string Id { get; } - /// DateTime when this session was created. - public DateTimeOffset CreatedDateTime { get; } - /// DateTime when this session was started by the client. - public DateTimeOffset? SessionStartDateTime { get; } - /// Whether or not the session is expired. - public bool SessionExpired { get; } - /// Unique Guid per each end-user device. This is to provide rate limiting and anti-hammering. If 'deviceCorrelationIdSetInClient' is true in this request, this 'deviceCorrelationId' must be null. - public string DeviceCorrelationId { get; } - /// Seconds the session should last for. Range is 60 to 86400 seconds. Default value is 600. - public int? AuthTokenTimeToLiveInSeconds { get; } + public string SessionId { get; } + /// Bearer token to provide authentication for the Vision SDK running on a client application. This Bearer token has limited permissions to perform only the required action and expires after the TTL time. It is also auditable. + public string AuthToken { get; } /// The current status of the session. - public FaceSessionStatus Status { get; } - /// The latest session audit result only populated if status == 'ResultAvailable'. - public LivenessSessionAuditEntry Result { get; } + public OperationState Status { get; } + /// The model version used for liveness classification. This is an optional parameter, and if this is not specified, then the latest supported model version will be chosen. + public LivenessModel? ModelVersion { get; } + /// The results of the liveness with verify session. + public LivenessWithVerifySessionResults Results { get; } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.Serialization.cs new file mode 100644 index 000000000000..97f9fadec5e6 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.Serialization.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessWithVerifySessionAttempt : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("attemptId"u8); + writer.WriteNumberValue(AttemptId); + writer.WritePropertyName("attemptStatus"u8); + writer.WriteStringValue(AttemptStatus.ToString()); + if (Optional.IsDefined(Result)) + { + writer.WritePropertyName("result"u8); + writer.WriteObjectValue(Result, options); + } + if (Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessWithVerifySessionAttempt IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessWithVerifySessionAttempt(document.RootElement, options); + } + + internal static LivenessWithVerifySessionAttempt DeserializeLivenessWithVerifySessionAttempt(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int attemptId = default; + OperationState attemptStatus = default; + LivenessWithVerifyResult result = default; + LivenessError error = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("attemptId"u8)) + { + attemptId = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("attemptStatus"u8)) + { + attemptStatus = new OperationState(property.Value.GetString()); + continue; + } + if (property.NameEquals("result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + result = LivenessWithVerifyResult.DeserializeLivenessWithVerifyResult(property.Value, options); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = LivenessError.DeserializeLivenessError(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessWithVerifySessionAttempt(attemptId, attemptStatus, result, error, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support writing '{options.Format}' format."); + } + } + + LivenessWithVerifySessionAttempt IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessWithVerifySessionAttempt(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessWithVerifySessionAttempt)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessWithVerifySessionAttempt FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessWithVerifySessionAttempt(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.cs new file mode 100644 index 000000000000..947837cf1967 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionAttempt.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Vision.Face +{ + /// The liveness with verify session attempt. + public partial class LivenessWithVerifySessionAttempt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + internal LivenessWithVerifySessionAttempt(int attemptId, OperationState attemptStatus) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + } + + /// Initializes a new instance of . + /// The attempt ID, start from 1. + /// The status of the attempt. + /// The result of the liveness with verify call, will be null if there is error. + /// The error of the liveness with verify call, will be null if there is result. + /// Keeps track of any properties unknown to the library. + internal LivenessWithVerifySessionAttempt(int attemptId, OperationState attemptStatus, LivenessWithVerifyResult result, LivenessError error, IDictionary serializedAdditionalRawData) + { + AttemptId = attemptId; + AttemptStatus = attemptStatus; + Result = result; + Error = error; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifySessionAttempt() + { + } + + /// The attempt ID, start from 1. + public int AttemptId { get; } + /// The status of the attempt. + public OperationState AttemptStatus { get; } + /// The result of the liveness with verify call, will be null if there is error. + public LivenessWithVerifyResult Result { get; } + /// The error of the liveness with verify call, will be null if there is result. + public LivenessError Error { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.Serialization.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.Serialization.cs new file mode 100644 index 000000000000..9a8dda439b7b --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.Serialization.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Vision.Face +{ + public partial class LivenessWithVerifySessionResults : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("verifyReferences"u8); + writer.WriteStartArray(); + foreach (var item in VerifyReferences) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("attempts"u8); + writer.WriteStartArray(); + foreach (var item in Attempts) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LivenessWithVerifySessionResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLivenessWithVerifySessionResults(document.RootElement, options); + } + + internal static LivenessWithVerifySessionResults DeserializeLivenessWithVerifySessionResults(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList verifyReferences = default; + IReadOnlyList attempts = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("verifyReferences"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(LivenessWithVerifyReference.DeserializeLivenessWithVerifyReference(item, options)); + } + verifyReferences = array; + continue; + } + if (property.NameEquals("attempts"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(LivenessWithVerifySessionAttempt.DeserializeLivenessWithVerifySessionAttempt(item, options)); + } + attempts = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LivenessWithVerifySessionResults(verifyReferences, attempts, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support writing '{options.Format}' format."); + } + } + + LivenessWithVerifySessionResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessWithVerifySessionResults(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LivenessWithVerifySessionResults)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LivenessWithVerifySessionResults FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLivenessWithVerifySessionResults(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.cs new file mode 100644 index 000000000000..570a83f964c2 --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessWithVerifySessionResults.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.Vision.Face +{ + /// The results of the liveness with verify session. + public partial class LivenessWithVerifySessionResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The references used for face verification. + /// The attempts data of underlying liveness with verify call with the session. + /// or is null. + internal LivenessWithVerifySessionResults(IEnumerable verifyReferences, IEnumerable attempts) + { + Argument.AssertNotNull(verifyReferences, nameof(verifyReferences)); + Argument.AssertNotNull(attempts, nameof(attempts)); + + VerifyReferences = verifyReferences.ToList(); + Attempts = attempts.ToList(); + } + + /// Initializes a new instance of . + /// The references used for face verification. + /// The attempts data of underlying liveness with verify call with the session. + /// Keeps track of any properties unknown to the library. + internal LivenessWithVerifySessionResults(IReadOnlyList verifyReferences, IReadOnlyList attempts, IDictionary serializedAdditionalRawData) + { + VerifyReferences = verifyReferences; + Attempts = attempts; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal LivenessWithVerifySessionResults() + { + } + + /// The references used for face verification. + public IReadOnlyList VerifyReferences { get; } + /// The attempts data of underlying liveness with verify call with the session. + public IReadOnlyList Attempts { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/OperationState.cs b/sdk/face/Azure.AI.Vision.Face/src/Generated/OperationState.cs new file mode 100644 index 000000000000..11c8033fba6a --- /dev/null +++ b/sdk/face/Azure.AI.Vision.Face/src/Generated/OperationState.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.Vision.Face +{ + /// Enum describing allowed operation states. + public readonly partial struct OperationState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OperationState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NotStartedValue = "NotStarted"; + private const string RunningValue = "Running"; + private const string SucceededValue = "Succeeded"; + private const string FailedValue = "Failed"; + private const string CanceledValue = "Canceled"; + + /// The operation has not started. + public static OperationState NotStarted { get; } = new OperationState(NotStartedValue); + /// The operation is in progress. + public static OperationState Running { get; } = new OperationState(RunningValue); + /// The operation has completed successfully. + public static OperationState Succeeded { get; } = new OperationState(SucceededValue); + /// The operation has failed. + public static OperationState Failed { get; } = new OperationState(FailedValue); + /// The operation has been canceled by the user. + public static OperationState Canceled { get; } = new OperationState(CanceledValue); + /// Determines if two values are the same. + public static bool operator ==(OperationState left, OperationState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OperationState left, OperationState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OperationState(string value) => new OperationState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OperationState other && Equals(other); + /// + public bool Equals(OperationState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs b/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs index b793cf92c5e9..01e05583b87c 100644 --- a/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs +++ b/sdk/face/Azure.AI.Vision.Face/tests/Generated/Samples/Samples_FaceSessionClient.cs @@ -28,8 +28,7 @@ public void Example_LivenessSession_CreateLivenessSession_CreateLivenessSession( using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -38,6 +37,9 @@ public void Example_LivenessSession_CreateLivenessSession_CreateLivenessSession( JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -51,8 +53,7 @@ public async Task Example_LivenessSession_CreateLivenessSession_CreateLivenessSe using RequestContent content = RequestContent.Create(new { livenessOperationMode = "Passive", - sendResultsToClient = true, - deviceCorrelationIdSetInClient = true, + deviceCorrelationIdSetInClient = false, deviceCorrelationId = "your_device_correlation_id", authTokenTimeToLiveInSeconds = 60, }); @@ -61,6 +62,9 @@ public async Task Example_LivenessSession_CreateLivenessSession_CreateLivenessSe JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; Console.WriteLine(result.GetProperty("sessionId").ToString()); Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -73,12 +77,11 @@ public void Example_LivenessSession_CreateLivenessSession_CreateLivenessSession_ CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; - Response response = client.CreateLivenessSession(body); + Response response = client.CreateLivenessSession(body); } [Test] @@ -91,12 +94,11 @@ public async Task Example_LivenessSession_CreateLivenessSession_CreateLivenessSe CreateLivenessSessionContent body = new CreateLivenessSessionContent(LivenessOperationMode.Passive) { - SendResultsToClient = true, - DeviceCorrelationIdSetInClient = true, + DeviceCorrelationIdSetInClient = false, DeviceCorrelationId = "your_device_correlation_id", AuthTokenTimeToLiveInSeconds = 60, }; - Response response = await client.CreateLivenessSessionAsync(body); + Response response = await client.CreateLivenessSessionAsync(body); } [Test] @@ -136,10 +138,11 @@ public void Example_LivenessSession_GetLivenessSessionResult_GetLivenessSessionR Response response = client.GetLivenessSessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -153,10 +156,11 @@ public async Task Example_LivenessSession_GetLivenessSessionResult_GetLivenessSe Response response = await client.GetLivenessSessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -183,128 +187,76 @@ public async Task Example_LivenessSession_GetLivenessSessionResult_GetLivenessSe [Test] [Ignore("Only validating compilation of examples")] - public void Example_LivenessSession_GetLivenessSessions_GetLivenessSessions() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessSessions("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessSession_GetLivenessSessions_GetLivenessSessions_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = await client.GetLivenessSessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_LivenessSession_GetLivenessSessions_GetLivenessSessions_Convenience() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = client.GetLivenessSessions(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessSession_GetLivenessSessions_GetLivenessSessions_Convenience_Async() + public void Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response> response = await client.GetLivenessSessionsAsync(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); + using RequestContent content = null; + Response response = client.CreateLivenessWithVerifySession(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries_Async() + public async Task Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession_Async() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); + using RequestContent content = null; + Response response = await client.CreateLivenessWithVerifySessionAsync(content, null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries_Convenience() + public void Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession_Convenience() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response> response = client.GetLivenessSessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); + CreateLivenessWithVerifySessionContent body = null; + Response response = client.CreateLivenessWithVerifySession(body); } [Test] [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessSessionAuditEntries_GetLivenessSessionAuditEntries_Convenience_Async() + public async Task Example_LivenessWithVerifySession_CreateLivenessWithVerifySession_CreateLivenessWithVerifySession_Convenience_Async() { Uri endpoint = new Uri(""); AzureKeyCredential credential = new AzureKeyCredential(""); FaceSessionClient client = new FaceSessionClient(endpoint, credential); - Response> response = await client.GetLivenessSessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); + CreateLivenessWithVerifySessionContent body = null; + Response response = await client.CreateLivenessWithVerifySessionAsync(body); } [Test] @@ -344,10 +296,17 @@ public void Example_LivenessWithVerifySession_GetLivenessWithVerifySessionResult Response response = client.GetLivenessWithVerifySessionResult("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -361,10 +320,17 @@ public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySession Response response = await client.GetLivenessWithVerifySessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e", null); JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result.GetProperty("id").ToString()); - Console.WriteLine(result.GetProperty("createdDateTime").ToString()); - Console.WriteLine(result.GetProperty("sessionExpired").ToString()); + Console.WriteLine(result.GetProperty("sessionId").ToString()); + Console.WriteLine(result.GetProperty("authToken").ToString()); Console.WriteLine(result.GetProperty("status").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("referenceType").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("top").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("left").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("width").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("faceRectangle").GetProperty("height").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("verifyReferences")[0].GetProperty("qualityForRecognition").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptId").ToString()); + Console.WriteLine(result.GetProperty("results").GetProperty("attempts")[0].GetProperty("attemptStatus").ToString()); } [Test] @@ -389,132 +355,6 @@ public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySession Response response = await client.GetLivenessWithVerifySessionResultAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); } - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessWithVerifySessions("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = await client.GetLivenessWithVerifySessionsAsync("00000000-0000-0000-0000-000000000000", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("createdDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("sessionExpired").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions_Convenience() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = client.GetLivenessWithVerifySessions(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_LivenessWithVerifySession_GetLivenessWithVerifySessions_GetLivenessWithVerifySessions_Convenience_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = await client.GetLivenessWithVerifySessionsAsync(); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e", "0", 20, null); - - JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; - Console.WriteLine(result[0].GetProperty("id").ToString()); - Console.WriteLine(result[0].GetProperty("sessionId").ToString()); - Console.WriteLine(result[0].GetProperty("requestId").ToString()); - Console.WriteLine(result[0].GetProperty("clientRequestId").ToString()); - Console.WriteLine(result[0].GetProperty("receivedDateTime").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("url").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("method").ToString()); - Console.WriteLine(result[0].GetProperty("request").GetProperty("contentType").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("body").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("statusCode").ToString()); - Console.WriteLine(result[0].GetProperty("response").GetProperty("latencyInMilliseconds").ToString()); - Console.WriteLine(result[0].GetProperty("digest").ToString()); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public void Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries_Convenience() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = client.GetLivenessWithVerifySessionAuditEntries("b12e033e-bda7-4b83-a211-e721c661f30e"); - } - - [Test] - [Ignore("Only validating compilation of examples")] - public async Task Example_FaceSessionClient_GetLivenessWithVerifySessionAuditEntries_GetLivenessWithVerifySessionAuditEntries_Convenience_Async() - { - Uri endpoint = new Uri(""); - AzureKeyCredential credential = new AzureKeyCredential(""); - FaceSessionClient client = new FaceSessionClient(endpoint, credential); - - Response> response = await client.GetLivenessWithVerifySessionAuditEntriesAsync("b12e033e-bda7-4b83-a211-e721c661f30e"); - } - [Test] [Ignore("Only validating compilation of examples")] public void Example_FaceSessionClient_DetectFromSessionImage_DetectFromSessionImageId() diff --git a/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml b/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml index b1904254ab7c..af7ac2e413a5 100644 --- a/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml +++ b/sdk/face/Azure.AI.Vision.Face/tsp-location.yaml @@ -1,5 +1,4 @@ directory: specification/ai/Face -commit: 06c18ef1f7fa1fd30744f6d681b7281c18396bdf +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs -additionalDirectories: [] - +additionalDirectories: diff --git a/sdk/healthdataaiservices/Azure.Health.Deidentification/tsp-location.yaml b/sdk/healthdataaiservices/Azure.Health.Deidentification/tsp-location.yaml index 9fd7c2585db2..7dc2f12e59fd 100644 --- a/sdk/healthdataaiservices/Azure.Health.Deidentification/tsp-location.yaml +++ b/sdk/healthdataaiservices/Azure.Health.Deidentification/tsp-location.yaml @@ -1,5 +1,4 @@ directory: specification/healthdataaiservices/HealthDataAIServices.DeidServices +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs -commit: 462574dbd02088c209bb1da3eef0d93f699e8de2 -additionalDirectories: [] - +additionalDirectories: diff --git a/sdk/healthinsights/Azure.Health.Insights.RadiologyInsights/tsp-location.yaml b/sdk/healthinsights/Azure.Health.Insights.RadiologyInsights/tsp-location.yaml index f37e9e56b97d..76db52774fe7 100644 --- a/sdk/healthinsights/Azure.Health.Insights.RadiologyInsights/tsp-location.yaml +++ b/sdk/healthinsights/Azure.Health.Insights.RadiologyInsights/tsp-location.yaml @@ -1,7 +1,4 @@ directory: specification/ai/HealthInsights/HealthInsights.RadiologyInsights -additionalDirectories: - - specification/ai/HealthInsights/HealthInsights.OpenAPI - - specification/ai/HealthInsights/HealthInsights.Common -commit: 1f1dcb6199544dd127964e91bd10118ecc21d7a8 +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs -cleanup: false +additionalDirectories: diff --git a/sdk/keyvault/Azure.Security.KeyVault.Administration/tsp-location.yaml b/sdk/keyvault/Azure.Security.KeyVault.Administration/tsp-location.yaml index 71f3993f51d8..3a2d140b1dad 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Administration/tsp-location.yaml +++ b/sdk/keyvault/Azure.Security.KeyVault.Administration/tsp-location.yaml @@ -1,9 +1,4 @@ directory: specification/keyvault/Security.KeyVault.Administration -commit: 462574dbd02088c209bb1da3eef0d93f699e8de2 +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs - -additionalDirectories: -- specification/keyvault/Security.KeyVault.BackupRestore/ -- specification/keyvault/Security.KeyVault.Common/ -- specification/keyvault/Security.KeyVault.RBAC/ -- specification/keyvault/Security.KeyVault.Settings/ +additionalDirectories: diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/Microsoft.App.DynamicSessions.sln b/sdk/microsoft.app/Microsoft.App.DynamicSessions/Microsoft.App.DynamicSessions.sln new file mode 100644 index 000000000000..1e89be24951a --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/Microsoft.App.DynamicSessions.sln @@ -0,0 +1,50 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.App.DynamicSessions", "src\Microsoft.App.DynamicSessions.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.App.DynamicSessions.Tests", "tests\Microsoft.App.DynamicSessions.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeExecution.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeExecution.cs new file mode 100644 index 000000000000..1ad451e837bc --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeExecution.cs @@ -0,0 +1,355 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Microsoft.App.DynamicSessions +{ + // Data plane generated sub-client. + /// The CodeExecution sub-client. + public partial class CodeExecution + { + private static readonly string[] AuthorizationScopes = new string[] { "https://dynamicsessions.io/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of CodeExecution for mocking. + protected CodeExecution() + { + } + + /// Initializes a new instance of CodeExecution. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// The management endpoint of the session pool. + /// The API version to use for this operation. + internal CodeExecution(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get the code execution result. + /// Session code execution id. + /// The user-assigned identifier of the session. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetSessionCodeExecutionResourceAsync(string executionId, string identifier, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(executionId, nameof(executionId)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetSessionCodeExecutionResourceAsync(executionId, identifier, context).ConfigureAwait(false); + return Response.FromValue(SessionCodeExecutionResource.FromResponse(response), response); + } + + /// Get the code execution result. + /// Session code execution id. + /// The user-assigned identifier of the session. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response GetSessionCodeExecutionResource(string executionId, string identifier, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(executionId, nameof(executionId)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetSessionCodeExecutionResource(executionId, identifier, context); + return Response.FromValue(SessionCodeExecutionResource.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get the code execution result. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Session code execution id. + /// The user-assigned identifier of the session. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetSessionCodeExecutionResourceAsync(string executionId, string identifier, RequestContext context) + { + Argument.AssertNotNullOrEmpty(executionId, nameof(executionId)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("CodeExecution.GetSessionCodeExecutionResource"); + scope.Start(); + try + { + using HttpMessage message = CreateGetSessionCodeExecutionResourceRequest(executionId, identifier, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get the code execution result. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// Session code execution id. + /// The user-assigned identifier of the session. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetSessionCodeExecutionResource(string executionId, string identifier, RequestContext context) + { + Argument.AssertNotNullOrEmpty(executionId, nameof(executionId)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("CodeExecution.GetSessionCodeExecutionResource"); + scope.Start(); + try + { + using HttpMessage message = CreateGetSessionCodeExecutionResourceRequest(executionId, identifier, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Execute code in a session. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The user-assigned identifier of the session. + /// The request to execute code. + /// The id of this execution operation. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task> ExecuteAsync(WaitUntil waitUntil, string identifier, SessionCodeExecutionRequest codeExecutionRequest, string operationId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(codeExecutionRequest, nameof(codeExecutionRequest)); + + using RequestContent content = codeExecutionRequest.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = await ExecuteAsync(waitUntil, identifier, content, operationId, context).ConfigureAwait(false); + return ProtocolOperationHelpers.Convert(response, FetchSessionCodeExecutionResultFromSessionCodeExecutionResource, ClientDiagnostics, "CodeExecution.Execute"); + } + + /// Execute code in a session. + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The user-assigned identifier of the session. + /// The request to execute code. + /// The id of this execution operation. + /// The cancellation token to use. + /// or is null. + /// + public virtual Operation Execute(WaitUntil waitUntil, string identifier, SessionCodeExecutionRequest codeExecutionRequest, string operationId = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(codeExecutionRequest, nameof(codeExecutionRequest)); + + using RequestContent content = codeExecutionRequest.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Operation response = Execute(waitUntil, identifier, content, operationId, context); + return ProtocolOperationHelpers.Convert(response, FetchSessionCodeExecutionResultFromSessionCodeExecutionResource, ClientDiagnostics, "CodeExecution.Execute"); + } + + /// + /// [Protocol Method] Execute code in a session. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The user-assigned identifier of the session. + /// The content to send as the body of the request. + /// The id of this execution operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual async Task> ExecuteAsync(WaitUntil waitUntil, string identifier, RequestContent content, string operationId = null, RequestContext context = null) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("CodeExecution.Execute"); + scope.Start(); + try + { + using HttpMessage message = CreateExecuteRequest(identifier, content, operationId, context); + return await ProtocolOperationHelpers.ProcessMessageAsync(_pipeline, message, ClientDiagnostics, "CodeExecution.Execute", OperationFinalStateVia.OperationLocation, context, waitUntil).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Execute code in a session. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// if the method should wait to return until the long-running operation has completed on the service; if it should return after starting the operation. For more information on long-running operations, please see Azure.Core Long-Running Operation samples. + /// The user-assigned identifier of the session. + /// The content to send as the body of the request. + /// The id of this execution operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The representing an asynchronous operation on the service. + /// + public virtual Operation Execute(WaitUntil waitUntil, string identifier, RequestContent content, string operationId = null, RequestContext context = null) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("CodeExecution.Execute"); + scope.Start(); + try + { + using HttpMessage message = CreateExecuteRequest(identifier, content, operationId, context); + return ProtocolOperationHelpers.ProcessMessage(_pipeline, message, ClientDiagnostics, "CodeExecution.Execute", OperationFinalStateVia.OperationLocation, context, waitUntil); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateExecuteRequest(string identifier, RequestContent content, string operationId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier202); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/executions", false); + uri.AppendQuery("identifier", identifier, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + if (operationId != null) + { + request.Headers.Add("operation-id", operationId); + } + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetSessionCodeExecutionResourceRequest(string executionId, string identifier, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/executions/", false); + uri.AppendPath(executionId, true); + uri.AppendQuery("identifier", identifier, true); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier202; + private static ResponseClassifier ResponseClassifier202 => _responseClassifier202 ??= new StatusCodeClassifier(stackalloc ushort[] { 202 }); + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + + private SessionCodeExecutionResult FetchSessionCodeExecutionResultFromSessionCodeExecutionResource(Response response) + { + var resultJsonElement = JsonDocument.Parse(response.Content).RootElement.GetProperty("result"); + return SessionCodeExecutionResult.DeserializeSessionCodeExecutionResult(resultJsonElement); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeInputType.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeInputType.cs new file mode 100644 index 000000000000..6d931a411fcf --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/CodeInputType.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.App.DynamicSessions +{ + /// Code input type. + public readonly partial struct CodeInputType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CodeInputType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InlineValue = "Inline"; + private const string InlineBase64Value = "InlineBase64"; + private const string InlineTextValue = "InlineText"; + + /// Inline. + public static CodeInputType Inline { get; } = new CodeInputType(InlineValue); + /// InlineBase64. + public static CodeInputType InlineBase64 { get; } = new CodeInputType(InlineBase64Value); + /// InlineText. + public static CodeInputType InlineText { get; } = new CodeInputType(InlineTextValue); + /// Determines if two values are the same. + public static bool operator ==(CodeInputType left, CodeInputType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CodeInputType left, CodeInputType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CodeInputType(string value) => new CodeInputType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CodeInputType other && Equals(other); + /// + public bool Equals(CodeInputType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/CodeExecution.xml b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/CodeExecution.xml new file mode 100644 index 000000000000..1f7cf7d6e2b1 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/CodeExecution.xml @@ -0,0 +1,291 @@ + + + + + +This sample shows how to call GetSessionCodeExecutionResourceAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier"); +]]> +This sample shows how to call GetSessionCodeExecutionResourceAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier"); +]]> + + + +This sample shows how to call GetSessionCodeExecutionResource. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier"); +]]> +This sample shows how to call GetSessionCodeExecutionResource. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier"); +]]> + + + +This sample shows how to call GetSessionCodeExecutionResourceAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("identifier").ToString()); +Console.WriteLine(result.GetProperty("executionType").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +]]> +This sample shows how to call GetSessionCodeExecutionResourceAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("identifier").ToString()); +Console.WriteLine(result.GetProperty("executionType").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +]]> + + + +This sample shows how to call GetSessionCodeExecutionResource and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("identifier").ToString()); +Console.WriteLine(result.GetProperty("executionType").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +]]> +This sample shows how to call GetSessionCodeExecutionResource and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("id").ToString()); +Console.WriteLine(result.GetProperty("identifier").ToString()); +Console.WriteLine(result.GetProperty("executionType").ToString()); +Console.WriteLine(result.GetProperty("status").ToString()); +]]> + + + +This sample shows how to call ExecuteAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); +Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); +SessionCodeExecutionResult responseData = operation.Value; +]]> +This sample shows how to call ExecuteAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); +Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); +SessionCodeExecutionResult responseData = operation.Value; +]]> +This sample shows how to call ExecuteAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Synchronous, "print(7*9)", 60L); +Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); +SessionCodeExecutionResult responseData = operation.Value; +]]> + + + +This sample shows how to call Execute. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); +Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); +SessionCodeExecutionResult responseData = operation.Value; +]]> +This sample shows how to call Execute. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); +Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); +SessionCodeExecutionResult responseData = operation.Value; +]]> +This sample shows how to call Execute. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Synchronous, "print(7*9)", 60L); +Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); +SessionCodeExecutionResult responseData = operation.Value; +]]> + + + +This sample shows how to call ExecuteAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = RequestContent.Create(new +{ + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, +}); +Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call ExecuteAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = RequestContent.Create(new +{ + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, +}); +Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call ExecuteAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = RequestContent.Create(new +{ + codeInputType = "Inline", + executionType = "Synchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, +}); +Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call Execute and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = RequestContent.Create(new +{ + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, +}); +Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call Execute and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = RequestContent.Create(new +{ + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, +}); +Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> +This sample shows how to call Execute and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = RequestContent.Create(new +{ + codeInputType = "Inline", + executionType = "Synchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, +}); +Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", content); +BinaryData responseData = operation.Value; + +JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/SessionResourceFiles.xml b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/SessionResourceFiles.xml new file mode 100644 index 000000000000..b756e760389f --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Docs/SessionResourceFiles.xml @@ -0,0 +1,253 @@ + + + + + +This sample shows how to call GetSessionResourceFileAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetSessionResourceFileAsync("testfile", "testSessionIdentifier"); +]]> + + + +This sample shows how to call GetSessionResourceFile. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetSessionResourceFile("testfile", "testSessionIdentifier"); +]]> + + + +This sample shows how to call GetSessionResourceFileAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetSessionResourceFileAsync("testfile", "testSessionIdentifier", "/", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call GetSessionResourceFile and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetSessionResourceFile("testfile", "testSessionIdentifier", "/", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call DeleteAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.DeleteAsync("testfile", "testSessionIdentifier"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call Delete. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = client.Delete("testfile", "testSessionIdentifier"); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call UploadAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +UploadRequest body = null; +Response response = await client.UploadAsync("testSessionIdentifier", body); +]]> + + + +This sample shows how to call Upload. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +UploadRequest body = null; +Response response = client.Upload("testSessionIdentifier", body); +]]> + + + +This sample shows how to call UploadAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = null; +Response response = await client.UploadAsync("testSessionIdentifier", content, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call Upload and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +using RequestContent content = null; +Response response = client.Upload("testSessionIdentifier", content, null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("name").ToString()); +Console.WriteLine(result.GetProperty("type").ToString()); +Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +]]> + + + +This sample shows how to call GetContentAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetContentAsync("testfile", "testSessionIdentifier"); +]]> + + + +This sample shows how to call GetContent. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetContent("testfile", "testSessionIdentifier"); +]]> + + + +This sample shows how to call GetContentAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = await client.GetContentAsync("testfile", "testSessionIdentifier", "/", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetContent and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +Response response = client.GetContent("testfile", "testSessionIdentifier", "/", null); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call GetSessionResourceFilesAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +await foreach (SessionResourceFile item in client.GetSessionResourceFilesAsync("testSessionIdentifier")) +{ +} +]]> + + + +This sample shows how to call GetSessionResourceFiles. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +foreach (SessionResourceFile item in client.GetSessionResourceFiles("testSessionIdentifier")) +{ +} +]]> + + + +This sample shows how to call GetSessionResourceFilesAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +await foreach (BinaryData item in client.GetSessionResourceFilesAsync("testSessionIdentifier", "/", null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +} +]]> + + + +This sample shows how to call GetSessionResourceFiles and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + +foreach (BinaryData item in client.GetSessionResourceFiles("testSessionIdentifier", "/", null)) +{ + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); +} +]]> + + + \ No newline at end of file diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClient.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClient.cs new file mode 100644 index 000000000000..c6ea990624a9 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClient.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Microsoft.App.DynamicSessions +{ + // Data plane generated client. + /// The DynamicSessions service client. + public partial class DynamicSessionsClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://dynamicsessions.io/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of DynamicSessionsClient for mocking. + protected DynamicSessionsClient() + { + } + + /// Initializes a new instance of DynamicSessionsClient. + /// The management endpoint of the session pool. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public DynamicSessionsClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new DynamicSessionsClientOptions()) + { + } + + /// Initializes a new instance of DynamicSessionsClient. + /// The management endpoint of the session pool. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public DynamicSessionsClient(Uri endpoint, TokenCredential credential, DynamicSessionsClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new DynamicSessionsClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + } + + /// Initializes a new instance of CodeExecution. + /// The API version to use for this operation. + /// is null. + public virtual CodeExecution GetCodeExecutionClient(string apiVersion = "2024-10-02-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new CodeExecution(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of SessionResourceFiles. + /// The API version to use for this operation. + /// is null. + public virtual SessionResourceFiles GetSessionResourceFilesClient(string apiVersion = "2024-10-02-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new SessionResourceFiles(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, apiVersion); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClientOptions.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClientOptions.cs new file mode 100644 index 000000000000..31ad50ae5345 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/DynamicSessionsClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + /// Client options for DynamicSessionsClient. + public partial class DynamicSessionsClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2024_10_02_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2024-10-02-preview". + V2024_10_02_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of DynamicSessionsClientOptions. + public DynamicSessionsClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2024_10_02_Preview => "2024-10-02-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.Serialization.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.Serialization.cs new file mode 100644 index 000000000000..ba226423834c --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + public partial class ErrorResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ErrorResponse)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("error"u8); + JsonSerializer.Serialize(writer, Error); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ErrorResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ErrorResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeErrorResponse(document.RootElement, options); + } + + internal static ErrorResponse DeserializeErrorResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ResponseError error = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("error"u8)) + { + error = JsonSerializer.Deserialize(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ErrorResponse(error, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ErrorResponse)} does not support writing '{options.Format}' format."); + } + } + + ErrorResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeErrorResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ErrorResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ErrorResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeErrorResponse(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.cs new file mode 100644 index 000000000000..365411fe4646 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ErrorResponse.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using Azure; + +namespace Microsoft.App.DynamicSessions +{ + /// A response containing error details. + public partial class ErrorResponse + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The error object. + /// is null. + internal ErrorResponse(ResponseError error) + { + Argument.AssertNotNull(error, nameof(error)); + + Error = error; + } + + /// Initializes a new instance of . + /// The error object. + /// Keeps track of any properties unknown to the library. + internal ErrorResponse(ResponseError error, IDictionary serializedAdditionalRawData) + { + Error = error; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ErrorResponse() + { + } + + /// The error object. + public ResponseError Error { get; } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ExecutionType.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ExecutionType.cs new file mode 100644 index 000000000000..8a5b0220c472 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/ExecutionType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.App.DynamicSessions +{ + /// Execution Type. + public readonly partial struct ExecutionType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ExecutionType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SynchronousValue = "Synchronous"; + private const string AsynchronousValue = "Asynchronous"; + + /// Synchronous. + public static ExecutionType Synchronous { get; } = new ExecutionType(SynchronousValue); + /// Asynchronous. + public static ExecutionType Asynchronous { get; } = new ExecutionType(AsynchronousValue); + /// Determines if two values are the same. + public static bool operator ==(ExecutionType left, ExecutionType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ExecutionType left, ExecutionType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ExecutionType(string value) => new ExecutionType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ExecutionType other && Equals(other); + /// + public bool Equals(ExecutionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Argument.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..b29962ac493f --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.App.DynamicSessions +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..2f625026ca9e --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.App.DynamicSessions +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingList.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..d9cfe9c47a7f --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Microsoft.App.DynamicSessions +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..5c205ab87ff5 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/MultipartFormDataRequestContent.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/MultipartFormDataRequestContent.cs new file mode 100644 index 000000000000..e644801a470a --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/MultipartFormDataRequestContent.cs @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Globalization; +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Microsoft.App.DynamicSessions +{ + internal class MultipartFormDataRequestContent : RequestContent + { + private readonly System.Net.Http.MultipartFormDataContent _multipartContent; + private static readonly Random _random = new Random(); + private static readonly char[] _boundaryValues = "0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray(); + + public MultipartFormDataRequestContent() + { + _multipartContent = new System.Net.Http.MultipartFormDataContent(CreateBoundary()); + } + + public string ContentType + { + get + { + return _multipartContent.Headers.ContentType.ToString(); + } + } + + internal HttpContent HttpContent => _multipartContent; + + private static string CreateBoundary() + { + Span chars = new char[70]; + byte[] random = new byte[70]; + _random.NextBytes(random); + int mask = 255 >> 2; + for (int i = 0; i < 70; i++) + { + chars[i] = _boundaryValues[random[i] & mask]; + } + return chars.ToString(); + } + + public void Add(string content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new StringContent(content), name, filename, contentType); + } + + public void Add(int content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(long content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(float content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(double content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(decimal content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(bool content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content ? "true" : "false"; + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(Stream content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new StreamContent(content), name, filename, contentType); + } + + public void Add(byte[] content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new ByteArrayContent(content), name, filename, contentType); + } + + public void Add(BinaryData content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new ByteArrayContent(content.ToArray()), name, filename, contentType); + } + + private void Add(HttpContent content, string name, string filename, string contentType) + { + if (filename != null) + { + Argument.AssertNotNullOrEmpty(filename, nameof(filename)); + AddFilenameHeader(content, name, filename); + } + if (contentType != null) + { + Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); + AddContentTypeHeader(content, contentType); + } + _multipartContent.Add(content, name); + } + + public static void AddFilenameHeader(HttpContent content, string name, string filename) + { + ContentDispositionHeaderValue header = new ContentDispositionHeaderValue("form-data") { Name = name, FileName = filename }; + content.Headers.ContentDisposition = header; + } + + public static void AddContentTypeHeader(HttpContent content, string contentType) + { + MediaTypeHeaderValue header = new MediaTypeHeaderValue(contentType); + content.Headers.ContentType = header; + } + + public override bool TryComputeLength(out long length) + { + if (_multipartContent.Headers.ContentLength is long contentLength) + { + length = contentLength; + return true; + } + length = 0; + return false; + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { +#if NET6_0_OR_GREATER + _multipartContent.CopyTo(stream, default, cancellationToken); +#else +#pragma warning disable AZC0107 + _multipartContent.CopyToAsync(stream).EnsureCompleted(); +#pragma warning restore AZC0107 +#endif + } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { +#if NET6_0_OR_GREATER + await _multipartContent.CopyToAsync(stream, cancellationToken).ConfigureAwait(false); +#else + await _multipartContent.CopyToAsync(stream).ConfigureAwait(false); +#endif + } + + public override void Dispose() + { + _multipartContent.Dispose(); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Optional.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..e39a6bf9bdee --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Microsoft.App.DynamicSessions +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..fa00656bf0f9 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsClientBuilderExtensions.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsClientBuilderExtensions.cs new file mode 100644 index 000000000000..7ef784e1b0cb --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core.Extensions; +using Microsoft.App.DynamicSessions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class MicrosoftAppDynamicSessionsClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// The management endpoint of the session pool. + public static IAzureClientBuilder AddDynamicSessionsClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new DynamicSessionsClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddDynamicSessionsClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsModelFactory.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsModelFactory.cs new file mode 100644 index 000000000000..9dde97cc16ee --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/MicrosoftAppDynamicSessionsModelFactory.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; +using Azure; + +namespace Microsoft.App.DynamicSessions +{ + /// Model factory for models. + public static partial class MicrosoftAppDynamicSessionsModelFactory + { + /// Initializes a new instance of . + /// The name of the file. + /// The type of the session resource file. + /// The type of the content of this file. + /// The size of the file. + /// The date time in RFC3339 format when the file was last modified. + /// A new instance for mocking. + public static SessionResourceFile SessionResourceFile(string name = null, string type = null, string contentType = null, long? sizeInBytes = null, DateTimeOffset lastModifiedAt = default) + { + return new SessionResourceFile( + name, + type, + contentType, + sizeInBytes, + lastModifiedAt, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Session code execution id. + /// The identifier of the session. + /// The execution type of the code execution request. + /// The status of the code execution operation, indicates whether succeeded or not. + /// The error of this code execution if failed. + /// The result of this code execution operation. + /// A new instance for mocking. + public static SessionCodeExecutionResource SessionCodeExecutionResource(string id = null, string identifier = null, ExecutionType executionType = default, OperationState status = default, ErrorResponse error = null, SessionCodeExecutionResult result = null) + { + return new SessionCodeExecutionResource( + id, + identifier, + executionType, + status, + error, + result, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The error object. + /// A new instance for mocking. + public static ErrorResponse ErrorResponse(ResponseError error = null) + { + return new ErrorResponse(error, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The standard output of the code execution. + /// The standard error of the code execution. + /// The result of the code execution. The type of this field is same as the type of actual result of the code execution after being Json serialized. + /// The execution time of the code in milliseconds. + /// A new instance for mocking. + public static SessionCodeExecutionResult SessionCodeExecutionResult(string stdout = null, string stderr = null, BinaryData executionResult = null, long? executionTimeInMilliseconds = null) + { + return new SessionCodeExecutionResult(stdout, stderr, executionResult, executionTimeInMilliseconds, serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/OperationState.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/OperationState.cs new file mode 100644 index 000000000000..d2bcf46d8694 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/OperationState.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Microsoft.App.DynamicSessions +{ + /// Enum describing allowed operation states. + public readonly partial struct OperationState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OperationState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NotStartedValue = "NotStarted"; + private const string RunningValue = "Running"; + private const string SucceededValue = "Succeeded"; + private const string FailedValue = "Failed"; + private const string CanceledValue = "Canceled"; + + /// The operation has not started. + public static OperationState NotStarted { get; } = new OperationState(NotStartedValue); + /// The operation is in progress. + public static OperationState Running { get; } = new OperationState(RunningValue); + /// The operation has completed successfully. + public static OperationState Succeeded { get; } = new OperationState(SucceededValue); + /// The operation has failed. + public static OperationState Failed { get; } = new OperationState(FailedValue); + /// The operation has been canceled by the user. + public static OperationState Canceled { get; } = new OperationState(CanceledValue); + /// Determines if two values are the same. + public static bool operator ==(OperationState left, OperationState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OperationState left, OperationState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OperationState(string value) => new OperationState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OperationState other && Equals(other); + /// + public bool Equals(OperationState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.Serialization.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.Serialization.cs new file mode 100644 index 000000000000..f371b326529b --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.Serialization.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + public partial class SessionCodeExecutionRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionCodeExecutionRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("codeInputType"u8); + writer.WriteStringValue(CodeInputType.ToString()); + writer.WritePropertyName("executionType"u8); + writer.WriteStringValue(ExecutionType.ToString()); + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code); + writer.WritePropertyName("timeoutInSeconds"u8); + writer.WriteNumberValue(TimeoutInSeconds); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SessionCodeExecutionRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionCodeExecutionRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSessionCodeExecutionRequest(document.RootElement, options); + } + + internal static SessionCodeExecutionRequest DeserializeSessionCodeExecutionRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CodeInputType codeInputType = default; + ExecutionType executionType = default; + string code = default; + long timeoutInSeconds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("codeInputType"u8)) + { + codeInputType = new CodeInputType(property.Value.GetString()); + continue; + } + if (property.NameEquals("executionType"u8)) + { + executionType = new ExecutionType(property.Value.GetString()); + continue; + } + if (property.NameEquals("code"u8)) + { + code = property.Value.GetString(); + continue; + } + if (property.NameEquals("timeoutInSeconds"u8)) + { + timeoutInSeconds = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SessionCodeExecutionRequest(codeInputType, executionType, code, timeoutInSeconds, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SessionCodeExecutionRequest)} does not support writing '{options.Format}' format."); + } + } + + SessionCodeExecutionRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionCodeExecutionRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SessionCodeExecutionRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SessionCodeExecutionRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionCodeExecutionRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.cs new file mode 100644 index 000000000000..b6197c19e287 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionRequest.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.App.DynamicSessions +{ + /// The request to execute code. + public partial class SessionCodeExecutionRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The code input type of the code execution request. + /// The execution type of the code execution request. + /// The string of the code to execute, based on CodeInputType. + /// Code execution timeout in seconds. + /// is null. + public SessionCodeExecutionRequest(CodeInputType codeInputType, ExecutionType executionType, string code, long timeoutInSeconds) + { + Argument.AssertNotNull(code, nameof(code)); + + CodeInputType = codeInputType; + ExecutionType = executionType; + Code = code; + TimeoutInSeconds = timeoutInSeconds; + } + + /// Initializes a new instance of . + /// The code input type of the code execution request. + /// The execution type of the code execution request. + /// The string of the code to execute, based on CodeInputType. + /// Code execution timeout in seconds. + /// Keeps track of any properties unknown to the library. + internal SessionCodeExecutionRequest(CodeInputType codeInputType, ExecutionType executionType, string code, long timeoutInSeconds, IDictionary serializedAdditionalRawData) + { + CodeInputType = codeInputType; + ExecutionType = executionType; + Code = code; + TimeoutInSeconds = timeoutInSeconds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SessionCodeExecutionRequest() + { + } + + /// The code input type of the code execution request. + public CodeInputType CodeInputType { get; } + /// The execution type of the code execution request. + public ExecutionType ExecutionType { get; } + /// The string of the code to execute, based on CodeInputType. + public string Code { get; } + /// Code execution timeout in seconds. + public long TimeoutInSeconds { get; } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.Serialization.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.Serialization.cs new file mode 100644 index 000000000000..52ec4ca64384 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.Serialization.cs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + public partial class SessionCodeExecutionResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionCodeExecutionResource)} does not support writing '{format}' format."); + } + + if (options.Format != "W") + { + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + } + writer.WritePropertyName("identifier"u8); + writer.WriteStringValue(Identifier); + writer.WritePropertyName("executionType"u8); + writer.WriteStringValue(ExecutionType.ToString()); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + writer.WriteObjectValue(Error, options); + } + if (Optional.IsDefined(Result)) + { + writer.WritePropertyName("result"u8); + writer.WriteObjectValue(Result, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SessionCodeExecutionResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionCodeExecutionResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSessionCodeExecutionResource(document.RootElement, options); + } + + internal static SessionCodeExecutionResource DeserializeSessionCodeExecutionResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + string identifier = default; + ExecutionType executionType = default; + OperationState status = default; + ErrorResponse error = default; + SessionCodeExecutionResult result = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("identifier"u8)) + { + identifier = property.Value.GetString(); + continue; + } + if (property.NameEquals("executionType"u8)) + { + executionType = new ExecutionType(property.Value.GetString()); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new OperationState(property.Value.GetString()); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = ErrorResponse.DeserializeErrorResponse(property.Value, options); + continue; + } + if (property.NameEquals("result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + result = SessionCodeExecutionResult.DeserializeSessionCodeExecutionResult(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SessionCodeExecutionResource( + id, + identifier, + executionType, + status, + error, + result, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SessionCodeExecutionResource)} does not support writing '{options.Format}' format."); + } + } + + SessionCodeExecutionResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionCodeExecutionResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SessionCodeExecutionResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SessionCodeExecutionResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionCodeExecutionResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.cs new file mode 100644 index 000000000000..78ed209c1e62 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResource.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.App.DynamicSessions +{ + /// The session code execution resource. + public partial class SessionCodeExecutionResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier of the session. + /// The execution type of the code execution request. + /// The status of the code execution operation, indicates whether succeeded or not. + /// is null. + internal SessionCodeExecutionResource(string identifier, ExecutionType executionType, OperationState status) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + + Identifier = identifier; + ExecutionType = executionType; + Status = status; + } + + /// Initializes a new instance of . + /// Session code execution id. + /// The identifier of the session. + /// The execution type of the code execution request. + /// The status of the code execution operation, indicates whether succeeded or not. + /// The error of this code execution if failed. + /// The result of this code execution operation. + /// Keeps track of any properties unknown to the library. + internal SessionCodeExecutionResource(string id, string identifier, ExecutionType executionType, OperationState status, ErrorResponse error, SessionCodeExecutionResult result, IDictionary serializedAdditionalRawData) + { + Id = id; + Identifier = identifier; + ExecutionType = executionType; + Status = status; + Error = error; + Result = result; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SessionCodeExecutionResource() + { + } + + /// Session code execution id. + public string Id { get; } + /// The identifier of the session. + public string Identifier { get; } + /// The execution type of the code execution request. + public ExecutionType ExecutionType { get; } + /// The status of the code execution operation, indicates whether succeeded or not. + public OperationState Status { get; } + /// The error of this code execution if failed. + public ErrorResponse Error { get; } + /// The result of this code execution operation. + public SessionCodeExecutionResult Result { get; } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.Serialization.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.Serialization.cs new file mode 100644 index 000000000000..87bb5de51244 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.Serialization.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + public partial class SessionCodeExecutionResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionCodeExecutionResult)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Stdout)) + { + writer.WritePropertyName("stdout"u8); + writer.WriteStringValue(Stdout); + } + if (Optional.IsDefined(Stderr)) + { + writer.WritePropertyName("stderr"u8); + writer.WriteStringValue(Stderr); + } + if (Optional.IsDefined(ExecutionResult)) + { + writer.WritePropertyName("executionResult"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ExecutionResult); +#else + using (JsonDocument document = JsonDocument.Parse(ExecutionResult, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(ExecutionTimeInMilliseconds)) + { + writer.WritePropertyName("executionTimeInMilliseconds"u8); + writer.WriteNumberValue(ExecutionTimeInMilliseconds.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SessionCodeExecutionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionCodeExecutionResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSessionCodeExecutionResult(document.RootElement, options); + } + + internal static SessionCodeExecutionResult DeserializeSessionCodeExecutionResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string stdout = default; + string stderr = default; + BinaryData executionResult = default; + long? executionTimeInMilliseconds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("stdout"u8)) + { + stdout = property.Value.GetString(); + continue; + } + if (property.NameEquals("stderr"u8)) + { + stderr = property.Value.GetString(); + continue; + } + if (property.NameEquals("executionResult"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + executionResult = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("executionTimeInMilliseconds"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + executionTimeInMilliseconds = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SessionCodeExecutionResult(stdout, stderr, executionResult, executionTimeInMilliseconds, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SessionCodeExecutionResult)} does not support writing '{options.Format}' format."); + } + } + + SessionCodeExecutionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionCodeExecutionResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SessionCodeExecutionResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SessionCodeExecutionResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionCodeExecutionResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.cs new file mode 100644 index 000000000000..56244e575e1d --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionCodeExecutionResult.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.App.DynamicSessions +{ + /// The result of the code execution. + public partial class SessionCodeExecutionResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal SessionCodeExecutionResult() + { + } + + /// Initializes a new instance of . + /// The standard output of the code execution. + /// The standard error of the code execution. + /// The result of the code execution. The type of this field is same as the type of actual result of the code execution after being Json serialized. + /// The execution time of the code in milliseconds. + /// Keeps track of any properties unknown to the library. + internal SessionCodeExecutionResult(string stdout, string stderr, BinaryData executionResult, long? executionTimeInMilliseconds, IDictionary serializedAdditionalRawData) + { + Stdout = stdout; + Stderr = stderr; + ExecutionResult = executionResult; + ExecutionTimeInMilliseconds = executionTimeInMilliseconds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The standard output of the code execution. + public string Stdout { get; } + /// The standard error of the code execution. + public string Stderr { get; } + /// + /// The result of the code execution. The type of this field is same as the type of actual result of the code execution after being Json serialized. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ExecutionResult { get; } + /// The execution time of the code in milliseconds. + public long? ExecutionTimeInMilliseconds { get; } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.Serialization.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.Serialization.cs new file mode 100644 index 000000000000..a2c681e9d404 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.Serialization.cs @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + public partial class SessionResourceFile : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionResourceFile)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (Optional.IsDefined(ContentType)) + { + writer.WritePropertyName("contentType"u8); + writer.WriteStringValue(ContentType); + } + if (Optional.IsDefined(SizeInBytes)) + { + writer.WritePropertyName("sizeInBytes"u8); + writer.WriteNumberValue(SizeInBytes.Value); + } + writer.WritePropertyName("lastModifiedAt"u8); + writer.WriteStringValue(LastModifiedAt, "O"); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SessionResourceFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SessionResourceFile)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSessionResourceFile(document.RootElement, options); + } + + internal static SessionResourceFile DeserializeSessionResourceFile(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string type = default; + string contentType = default; + long? sizeInBytes = default; + DateTimeOffset lastModifiedAt = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (property.NameEquals("contentType"u8)) + { + contentType = property.Value.GetString(); + continue; + } + if (property.NameEquals("sizeInBytes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sizeInBytes = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("lastModifiedAt"u8)) + { + lastModifiedAt = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SessionResourceFile( + name, + type, + contentType, + sizeInBytes, + lastModifiedAt, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SessionResourceFile)} does not support writing '{options.Format}' format."); + } + } + + SessionResourceFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionResourceFile(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SessionResourceFile)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SessionResourceFile FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSessionResourceFile(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.cs new file mode 100644 index 000000000000..5438b780714c --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFile.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Microsoft.App.DynamicSessions +{ + /// Code execution file resource. + public partial class SessionResourceFile + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the file. + /// The type of the session resource file. + /// The date time in RFC3339 format when the file was last modified. + /// or is null. + internal SessionResourceFile(string name, string type, DateTimeOffset lastModifiedAt) + { + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(type, nameof(type)); + + Name = name; + Type = type; + LastModifiedAt = lastModifiedAt; + } + + /// Initializes a new instance of . + /// The name of the file. + /// The type of the session resource file. + /// The type of the content of this file. + /// The size of the file. + /// The date time in RFC3339 format when the file was last modified. + /// Keeps track of any properties unknown to the library. + internal SessionResourceFile(string name, string type, string contentType, long? sizeInBytes, DateTimeOffset lastModifiedAt, IDictionary serializedAdditionalRawData) + { + Name = name; + Type = type; + ContentType = contentType; + SizeInBytes = sizeInBytes; + LastModifiedAt = lastModifiedAt; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SessionResourceFile() + { + } + + /// The name of the file. + public string Name { get; } + /// The type of the session resource file. + public string Type { get; } + /// The type of the content of this file. + public string ContentType { get; } + /// The size of the file. + public long? SizeInBytes { get; } + /// The date time in RFC3339 format when the file was last modified. + public DateTimeOffset LastModifiedAt { get; } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFiles.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFiles.cs new file mode 100644 index 000000000000..d8e594dd3af7 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/SessionResourceFiles.cs @@ -0,0 +1,722 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Autorest.CSharp.Core; +using Azure; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Microsoft.App.DynamicSessions +{ + // Data plane generated sub-client. + /// The SessionResourceFiles sub-client. + public partial class SessionResourceFiles + { + private static readonly string[] AuthorizationScopes = new string[] { "https://dynamicsessions.io/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of SessionResourceFiles for mocking. + protected SessionResourceFiles() + { + } + + /// Initializes a new instance of SessionResourceFiles. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// The management endpoint of the session pool. + /// The API version to use for this operation. + internal SessionResourceFiles(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Get the file resource. + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetSessionResourceFileAsync(string name, string identifier, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetSessionResourceFileAsync(name, identifier, path, context).ConfigureAwait(false); + return Response.FromValue(SessionResourceFile.FromResponse(response), response); + } + + /// Get the file resource. + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response GetSessionResourceFile(string name, string identifier, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetSessionResourceFile(name, identifier, path, context); + return Response.FromValue(SessionResourceFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Get the file resource. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetSessionResourceFileAsync(string name, string identifier, string path, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.GetSessionResourceFile"); + scope.Start(); + try + { + using HttpMessage message = CreateGetSessionResourceFileRequest(name, identifier, path, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get the file resource. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetSessionResourceFile(string name, string identifier, string path, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.GetSessionResourceFile"); + scope.Start(); + try + { + using HttpMessage message = CreateGetSessionResourceFileRequest(name, identifier, path, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete the file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task DeleteAsync(string name, string identifier, string path = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.Delete"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteRequest(name, identifier, path, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + // The convenience method is omitted here because it has exactly the same parameter list as the corresponding protocol method + /// + /// [Protocol Method] Delete the file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Delete(string name, string identifier, string path = null, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.Delete"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteRequest(name, identifier, path, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Upload a file to a session. + /// The user-assigned identifier of the session. + /// Multipart body. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task> UploadAsync(string identifier, UploadRequest body, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await UploadAsync(identifier, content, content.ContentType, path, context).ConfigureAwait(false); + return Response.FromValue(SessionResourceFile.FromResponse(response), response); + } + + /// Upload a file to a session. + /// The user-assigned identifier of the session. + /// Multipart body. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// or is null. + /// + public virtual Response Upload(string identifier, UploadRequest body, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Upload(identifier, content, content.ContentType, path, context); + return Response.FromValue(SessionResourceFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Upload a file to a session. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The user-assigned identifier of the session. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task UploadAsync(string identifier, RequestContent content, string contentType, string path = null, RequestContext context = null) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.Upload"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadRequest(identifier, content, contentType, path, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Upload a file to a session. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The user-assigned identifier of the session. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Upload(string identifier, RequestContent content, string contentType, string path = null, RequestContext context = null) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.Upload"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadRequest(identifier, content, contentType, path, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Get the content of the file. + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual async Task> GetContentAsync(string name, string identifier, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetContentAsync(name, identifier, path, context).ConfigureAwait(false); + return Response.FromValue(response.Content, response); + } + + /// Get the content of the file. + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// + public virtual Response GetContent(string name, string identifier, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetContent(name, identifier, path, context); + return Response.FromValue(response.Content, response); + } + + /// + /// [Protocol Method] Get the content of the file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task GetContentAsync(string name, string identifier, string path, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.GetContent"); + scope.Start(); + try + { + using HttpMessage message = CreateGetContentRequest(name, identifier, path, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Get the content of the file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The name of the file. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response GetContent(string name, string identifier, string path, RequestContext context) + { + Argument.AssertNotNullOrEmpty(name, nameof(name)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + using var scope = ClientDiagnostics.CreateScope("SessionResourceFiles.GetContent"); + scope.Start(); + try + { + using HttpMessage message = CreateGetContentRequest(name, identifier, path, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// List the file resources. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// is null. + /// + public virtual AsyncPageable GetSessionResourceFilesAsync(string identifier, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetSessionResourceFilesRequest(identifier, path, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetSessionResourceFilesNextPageRequest(nextLink, identifier, path, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => SessionResourceFile.DeserializeSessionResourceFile(e), ClientDiagnostics, _pipeline, "SessionResourceFiles.GetSessionResourceFiles", "value", "nextLink", context); + } + + /// List the file resources. + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The cancellation token to use. + /// is null. + /// + public virtual Pageable GetSessionResourceFiles(string identifier, string path = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + + RequestContext context = cancellationToken.CanBeCanceled ? new RequestContext { CancellationToken = cancellationToken } : null; + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetSessionResourceFilesRequest(identifier, path, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetSessionResourceFilesNextPageRequest(nextLink, identifier, path, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => SessionResourceFile.DeserializeSessionResourceFile(e), ClientDiagnostics, _pipeline, "SessionResourceFiles.GetSessionResourceFiles", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List the file resources. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual AsyncPageable GetSessionResourceFilesAsync(string identifier, string path, RequestContext context) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetSessionResourceFilesRequest(identifier, path, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetSessionResourceFilesNextPageRequest(nextLink, identifier, path, context); + return GeneratorPageableHelpers.CreateAsyncPageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "SessionResourceFiles.GetSessionResourceFiles", "value", "nextLink", context); + } + + /// + /// [Protocol Method] List the file resources. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The user-assigned identifier of the session. + /// The path of the file after uploaded. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The from the service containing a list of objects. Details of the body schema for each item in the collection are in the Remarks section below. + /// + public virtual Pageable GetSessionResourceFiles(string identifier, string path, RequestContext context) + { + Argument.AssertNotNull(identifier, nameof(identifier)); + + HttpMessage FirstPageRequest(int? pageSizeHint) => CreateGetSessionResourceFilesRequest(identifier, path, context); + HttpMessage NextPageRequest(int? pageSizeHint, string nextLink) => CreateGetSessionResourceFilesNextPageRequest(nextLink, identifier, path, context); + return GeneratorPageableHelpers.CreatePageable(FirstPageRequest, NextPageRequest, e => BinaryData.FromString(e.GetRawText()), ClientDiagnostics, _pipeline, "SessionResourceFiles.GetSessionResourceFiles", "value", "nextLink", context); + } + + internal HttpMessage CreateGetSessionResourceFilesRequest(string identifier, string path, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files", false); + uri.AppendQuery("identifier", identifier, true); + uri.AppendQuery("api-version", _apiVersion, true); + if (path != null) + { + uri.AppendQuery("path", path, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetSessionResourceFileRequest(string name, string identifier, string path, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files/", false); + uri.AppendPath(name, true); + uri.AppendQuery("identifier", identifier, true); + uri.AppendQuery("api-version", _apiVersion, true); + if (path != null) + { + uri.AppendQuery("path", path, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteRequest(string name, string identifier, string path, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier204); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files/", false); + uri.AppendPath(name, true); + uri.AppendQuery("identifier", identifier, true); + uri.AppendQuery("api-version", _apiVersion, true); + if (path != null) + { + uri.AppendQuery("path", path, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUploadRequest(string identifier, RequestContent content, string contentType, string path, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files", false); + uri.AppendQuery("identifier", identifier, true); + uri.AppendQuery("api-version", _apiVersion, true); + if (path != null) + { + uri.AppendQuery("path", path, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetContentRequest(string name, string identifier, string path, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/files/", false); + uri.AppendPath(name, true); + uri.AppendPath("/content", false); + uri.AppendQuery("identifier", identifier, true); + uri.AppendQuery("api-version", _apiVersion, true); + if (path != null) + { + uri.AppendQuery("path", path, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/octet-stream"); + return message; + } + + internal HttpMessage CreateGetSessionResourceFilesNextPageRequest(string nextLink, string identifier, string path, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRawNextLink(nextLink, false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier204; + private static ResponseClassifier ResponseClassifier204 => _responseClassifier204 ??= new StatusCodeClassifier(stackalloc ushort[] { 204 }); + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.Serialization.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.Serialization.cs new file mode 100644 index 000000000000..b5630fdfa449 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.Serialization.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure; +using Azure.Core; + +namespace Microsoft.App.DynamicSessions +{ + public partial class UploadRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UploadRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(File)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(File), ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + UploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UploadRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUploadRequest(document.RootElement, options); + } + + internal static UploadRequest DeserializeUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream file = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file"u8)) + { + file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UploadRequest(file, serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(File, "file", "file", "application/octet-stream"); + return content; + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(UploadRequest)} does not support writing '{options.Format}' format."); + } + } + + UploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUploadRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UploadRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UploadRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUploadRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.cs new file mode 100644 index 000000000000..e4101c59cecf --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Generated/UploadRequest.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Microsoft.App.DynamicSessions +{ + /// The UploadRequest. + public partial class UploadRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The file to upload. + /// is null. + public UploadRequest(Stream file) + { + Argument.AssertNotNull(file, nameof(file)); + + File = file; + } + + /// Initializes a new instance of . + /// The file to upload. + /// Keeps track of any properties unknown to the library. + internal UploadRequest(Stream file, IDictionary serializedAdditionalRawData) + { + File = file; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal UploadRequest() + { + } + + /// The file to upload. + public Stream File { get; } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Microsoft.App.DynamicSessions.csproj b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Microsoft.App.DynamicSessions.csproj new file mode 100644 index 000000000000..66908b681557 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Microsoft.App.DynamicSessions.csproj @@ -0,0 +1,19 @@ + + + This is the Microsoft.App.DynamicSessions client library for developing .NET applications with rich experience. + Azure SDK Code Generation Microsoft.App.DynamicSessions for Azure Data Plane + 1.0.0-beta.1 + Microsoft.App.DynamicSessions + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Properties/AssemblyInfo.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..30c11b3b63b9 --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/src/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Microsoft.App.DynamicSessions.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_CodeExecution.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_CodeExecution.cs new file mode 100644 index 000000000000..8e0115b4ae8f --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_CodeExecution.cs @@ -0,0 +1,342 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Microsoft.App.DynamicSessions.Samples +{ + public partial class Samples_CodeExecution + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetCompleted() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("identifier").ToString()); + Console.WriteLine(result.GetProperty("executionType").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetCompleted_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("identifier").ToString()); + Console.WriteLine(result.GetProperty("executionType").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetCompleted_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetCompleted_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetRunning() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("identifier").ToString()); + Console.WriteLine(result.GetProperty("executionType").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetRunning_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("id").ToString()); + Console.WriteLine(result.GetProperty("identifier").ToString()); + Console.WriteLine(result.GetProperty("executionType").ToString()); + Console.WriteLine(result.GetProperty("status").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetRunning_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetSessionCodeExecutionResource("testExecutionId", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionCodeExecutionResource_GetSessionCodeExecutionResource_CodeExecutionGetRunning_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetSessionCodeExecutionResourceAsync("testExecutionId", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_CodeExecution_Execute_CodeExecutionExecuteAsyncCompleted() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = RequestContent.Create(new + { + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, + }); + Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_CodeExecution_Execute_CodeExecutionExecuteAsyncCompleted_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = RequestContent.Create(new + { + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, + }); + Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_CodeExecution_Execute_CodeExecutionExecuteAsyncCompleted_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); + Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); + SessionCodeExecutionResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_CodeExecution_Execute_CodeExecutionExecuteAsyncCompleted_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); + Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); + SessionCodeExecutionResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_CodeExecution_Execute_CodeExecutionExecuteAsyncRunning() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = RequestContent.Create(new + { + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, + }); + Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_CodeExecution_Execute_CodeExecutionExecuteAsyncRunning_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = RequestContent.Create(new + { + codeInputType = "Inline", + executionType = "Asynchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, + }); + Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_CodeExecution_Execute_CodeExecutionExecuteAsyncRunning_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); + Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); + SessionCodeExecutionResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_CodeExecution_Execute_CodeExecutionExecuteAsyncRunning_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Asynchronous, "print(7*9)", 60L); + Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); + SessionCodeExecutionResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_CodeExecution_Execute_CodeExecutionExecuteSync() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = RequestContent.Create(new + { + codeInputType = "Inline", + executionType = "Synchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, + }); + Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_CodeExecution_Execute_CodeExecutionExecuteSync_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = RequestContent.Create(new + { + codeInputType = "Inline", + executionType = "Synchronous", + code = "print(7*9)", + timeoutInSeconds = 60L, + }); + Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", content); + BinaryData responseData = operation.Value; + + JsonElement result = JsonDocument.Parse(responseData.ToStream()).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_CodeExecution_Execute_CodeExecutionExecuteSync_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Synchronous, "print(7*9)", 60L); + Operation operation = client.Execute(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); + SessionCodeExecutionResult responseData = operation.Value; + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_CodeExecution_Execute_CodeExecutionExecuteSync_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + CodeExecution client = new DynamicSessionsClient(endpoint, credential).GetCodeExecutionClient(apiVersion: "2024-10-02-preview"); + + SessionCodeExecutionRequest codeExecutionRequest = new SessionCodeExecutionRequest(CodeInputType.Inline, ExecutionType.Synchronous, "print(7*9)", 60L); + Operation operation = await client.ExecuteAsync(WaitUntil.Completed, "testSessionIdentifier", codeExecutionRequest); + SessionCodeExecutionResult responseData = operation.Value; + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_SessionResourceFiles.cs b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_SessionResourceFiles.cs new file mode 100644 index 000000000000..f1aa68e5c63d --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Generated/Samples/Samples_SessionResourceFiles.cs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Microsoft.App.DynamicSessions.Samples +{ + public partial class Samples_SessionResourceFiles + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFile_GetSessionResourceFile_SessionResourceFilesGet() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetSessionResourceFile("testfile", "testSessionIdentifier", "/", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFile_GetSessionResourceFile_SessionResourceFilesGet_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetSessionResourceFileAsync("testfile", "testSessionIdentifier", "/", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFile_GetSessionResourceFile_SessionResourceFilesGet_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetSessionResourceFile("testfile", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFile_GetSessionResourceFile_SessionResourceFilesGet_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetSessionResourceFileAsync("testfile", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFile_Delete_SessionResourceFilesDelete() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = client.Delete("testfile", "testSessionIdentifier"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFile_Delete_SessionResourceFilesDelete_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.DeleteAsync("testfile", "testSessionIdentifier"); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFiles_Upload_SessionResourceFilesUpload() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = null; + Response response = client.Upload("testSessionIdentifier", content, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFiles_Upload_SessionResourceFilesUpload_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + using RequestContent content = null; + Response response = await client.UploadAsync("testSessionIdentifier", content, null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFiles_Upload_SessionResourceFilesUpload_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + UploadRequest body = null; + Response response = client.Upload("testSessionIdentifier", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFiles_Upload_SessionResourceFilesUpload_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + UploadRequest body = null; + Response response = await client.UploadAsync("testSessionIdentifier", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFiles_GetContent_SessionResourceFilesGetContent() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetContent("testfile", "testSessionIdentifier", "/", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFiles_GetContent_SessionResourceFilesGetContent_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetContentAsync("testfile", "testSessionIdentifier", "/", null); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFiles_GetContent_SessionResourceFilesGetContent_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = client.GetContent("testfile", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFiles_GetContent_SessionResourceFilesGetContent_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + Response response = await client.GetContentAsync("testfile", "testSessionIdentifier"); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFile_GetSessionResourceFiles_SessionResourceFilesList() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + foreach (BinaryData item in client.GetSessionResourceFiles("testSessionIdentifier", "/", null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFile_GetSessionResourceFiles_SessionResourceFilesList_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + await foreach (BinaryData item in client.GetSessionResourceFilesAsync("testSessionIdentifier", "/", null)) + { + JsonElement result = JsonDocument.Parse(item.ToStream()).RootElement; + Console.WriteLine(result.GetProperty("name").ToString()); + Console.WriteLine(result.GetProperty("type").ToString()); + Console.WriteLine(result.GetProperty("lastModifiedAt").ToString()); + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SessionResourceFile_GetSessionResourceFiles_SessionResourceFilesList_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + foreach (SessionResourceFile item in client.GetSessionResourceFiles("testSessionIdentifier")) + { + } + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SessionResourceFile_GetSessionResourceFiles_SessionResourceFilesList_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SessionResourceFiles client = new DynamicSessionsClient(endpoint, credential).GetSessionResourceFilesClient(apiVersion: "2024-10-02-preview"); + + await foreach (SessionResourceFile item in client.GetSessionResourceFilesAsync("testSessionIdentifier")) + { + } + } + } +} diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Microsoft.App.DynamicSessions.Tests.csproj b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Microsoft.App.DynamicSessions.Tests.csproj new file mode 100644 index 000000000000..060a1cce65bd --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tests/Microsoft.App.DynamicSessions.Tests.csproj @@ -0,0 +1,19 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/sdk/microsoft.app/Microsoft.App.DynamicSessions/tsp-location.yaml b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tsp-location.yaml new file mode 100644 index 000000000000..512c833566ce --- /dev/null +++ b/sdk/microsoft.app/Microsoft.App.DynamicSessions/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/app/Microsoft.App.DynamicSessions +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ApiResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ApiResponseFormat.cs new file mode 100644 index 000000000000..a9d6dc151976 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ApiResponseFormat.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Possible API response formats. + internal readonly partial struct ApiResponseFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ApiResponseFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string TextValue = "text"; + private const string JsonObjectValue = "json_object"; + private const string JsonSchemaValue = "json_schema"; + + /// `text` format should be used for requests involving any sort of ToolCall. + public static ApiResponseFormat Text { get; } = new ApiResponseFormat(TextValue); + /// Using `json_object` format will limit the usage of ToolCall to only functions. + public static ApiResponseFormat JsonObject { get; } = new ApiResponseFormat(JsonObjectValue); + /// Using `json_schema` format will ensure the model matches the supplied JSON schema. + public static ApiResponseFormat JsonSchema { get; } = new ApiResponseFormat(JsonSchemaValue); + /// Determines if two values are the same. + public static bool operator ==(ApiResponseFormat left, ApiResponseFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ApiResponseFormat left, ApiResponseFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ApiResponseFormat(string value) => new ApiResponseFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ApiResponseFormat other && Equals(other); + /// + public bool Equals(ApiResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs index 54d84a05db04..590f2636f4bb 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.Serialization.cs @@ -76,13 +76,52 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteObjectValue(item, options); } writer.WriteEndArray(); - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + if (ToolResources != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); + } } - writer.WriteEndArray(); if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -143,7 +182,10 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW string model = default; string instructions = default; IReadOnlyList tools = default; - IReadOnlyList fileIds = default; + ToolResources toolResources = default; + float? temperature = default; + float? topP = default; + BinaryData responseFormat = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -209,14 +251,44 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW tools = array; continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("tool_resources"u8)) { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + if (property.Value.ValueKind == JsonValueKind.Null) { - array.Add(item.GetString()); + toolResources = null; + continue; + } + toolResources = ToolResources.DeserializeToolResources(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; } - fileIds = array; + responseFormat = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("metadata"u8)) @@ -249,7 +321,10 @@ internal static Assistant DeserializeAssistant(JsonElement element, ModelReaderW model, instructions, tools, - fileIds, + toolResources, + temperature, + topP, + responseFormat, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs index 34402e5480d9..09b938b95c0e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/Assistant.cs @@ -56,17 +56,29 @@ public partial class Assistant /// /// The collection of tools enabled for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. /// - /// A list of attached file IDs, ordered by creation date in ascending order. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// , , or is null. - internal Assistant(string id, DateTimeOffset createdAt, string name, string description, string model, string instructions, IEnumerable tools, IEnumerable fileIds, IReadOnlyDictionary metadata) + /// , or is null. + internal Assistant(string id, DateTimeOffset createdAt, string name, string description, string model, string instructions, IEnumerable tools, ToolResources toolResources, float? temperature, float? topP, IReadOnlyDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(model, nameof(model)); Argument.AssertNotNull(tools, nameof(tools)); - Argument.AssertNotNull(fileIds, nameof(fileIds)); Id = id; CreatedAt = createdAt; @@ -75,7 +87,9 @@ internal Assistant(string id, DateTimeOffset createdAt, string name, string desc Model = model; Instructions = instructions; Tools = tools.ToList(); - FileIds = fileIds.ToList(); + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; Metadata = metadata; } @@ -90,12 +104,26 @@ internal Assistant(string id, DateTimeOffset createdAt, string name, string desc /// /// The collection of tools enabled for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. /// - /// A list of attached file IDs, ordered by creation date in ascending order. + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal Assistant(string id, string @object, DateTimeOffset createdAt, string name, string description, string model, string instructions, IReadOnlyList tools, IReadOnlyList fileIds, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal Assistant(string id, string @object, DateTimeOffset createdAt, string name, string description, string model, string instructions, IReadOnlyList tools, ToolResources toolResources, float? temperature, float? topP, BinaryData responseFormat, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; @@ -105,7 +133,10 @@ internal Assistant(string id, string @object, DateTimeOffset createdAt, string n Model = model; Instructions = instructions; Tools = tools; - FileIds = fileIds; + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -131,11 +162,71 @@ internal Assistant() /// /// The collection of tools enabled for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IReadOnlyList Tools { get; } - /// A list of attached file IDs, ordered by creation date in ascending order. - public IReadOnlyList FileIds { get; } + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + public ToolResources ToolResources { get; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; } + /// + /// The response format of the tool calls used by this assistant. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs index d0f8a38f8d29..3e54e193e53e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.Serialization.cs @@ -82,15 +82,60 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } writer.WriteEndArray(); } - if (Optional.IsCollectionDefined(FileIds)) + if (Optional.IsDefined(ToolResources)) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + if (ToolResources != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -152,7 +197,10 @@ internal static AssistantCreationOptions DeserializeAssistantCreationOptions(Jso string description = default; string instructions = default; IList tools = default; - IList fileIds = default; + CreateToolResourcesOptions toolResources = default; + float? temperature = default; + float? topP = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -207,18 +255,44 @@ internal static AssistantCreationOptions DeserializeAssistantCreationOptions(Jso tools = array; continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("tool_resources"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { + toolResources = null; continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + toolResources = CreateToolResourcesOptions.DeserializeCreateToolResourcesOptions(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) { - array.Add(item.GetString()); + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; } - fileIds = array; + responseFormat = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("metadata"u8)) @@ -247,7 +321,10 @@ internal static AssistantCreationOptions DeserializeAssistantCreationOptions(Jso description, instructions, tools ?? new ChangeTrackingList(), - fileIds ?? new ChangeTrackingList(), + toolResources, + temperature, + topP, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs index 34372f563399..87275c6b0976 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantCreationOptions.cs @@ -54,7 +54,6 @@ public AssistantCreationOptions(string model) Model = model; Tools = new ChangeTrackingList(); - FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } @@ -66,19 +65,36 @@ public AssistantCreationOptions(string model) /// /// The collection of tools to enable for the new assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of previously uploaded file IDs to attach to the assistant. + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal AssistantCreationOptions(string model, string name, string description, string instructions, IList tools, IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal AssistantCreationOptions(string model, string name, string description, string instructions, IList tools, CreateToolResourcesOptions toolResources, float? temperature, float? topP, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { Model = model; Name = name; Description = description; Instructions = instructions; Tools = tools; - FileIds = fileIds; + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -99,11 +115,71 @@ internal AssistantCreationOptions() /// /// The collection of tools to enable for the new assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IList Tools { get; } - /// A list of previously uploaded file IDs to attach to the assistant. - public IList FileIds { get; } + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + public CreateToolResourcesOptions ToolResources { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The response format of the tool calls used by this assistant. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantStreamEvent.cs new file mode 100644 index 000000000000..3c35b2590d78 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantStreamEvent.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Each event in a server-sent events stream has an `event` and `data` property: + /// + /// ``` + /// event: thread.created + /// data: {"id": "thread_123", "object": "thread", ...} + /// ``` + /// + /// We emit events whenever a new object is created, transitions to a new state, or is being + /// streamed in parts (deltas). For example, we emit `thread.run.created` when a new run + /// is created, `thread.run.completed` when a run completes, and so on. When an Assistant chooses + /// to create a message during a run, we emit a `thread.message.created event`, a + /// `thread.message.in_progress` event, many `thread.message.delta` events, and finally a + /// `thread.message.completed` event. + /// + /// We may add additional events over time, so we recommend handling unknown events gracefully + /// in your code. + /// + public readonly partial struct AssistantStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadCreatedValue = "thread.created"; + private const string ThreadRunCreatedValue = "thread.run.created"; + private const string ThreadRunQueuedValue = "thread.run.queued"; + private const string ThreadRunInProgressValue = "thread.run.in_progress"; + private const string ThreadRunRequiresActionValue = "thread.run.requires_action"; + private const string ThreadRunCompletedValue = "thread.run.completed"; + private const string ThreadRunFailedValue = "thread.run.failed"; + private const string ThreadRunCancellingValue = "thread.run.cancelling"; + private const string ThreadRunCancelledValue = "thread.run.cancelled"; + private const string ThreadRunExpiredValue = "thread.run.expired"; + private const string ThreadRunStepCreatedValue = "thread.run.step.created"; + private const string ThreadRunStepInProgressValue = "thread.run.step.in_progress"; + private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; + private const string ThreadRunStepCompletedValue = "thread.run.step.completed"; + private const string ThreadRunStepFailedValue = "thread.run.step.failed"; + private const string ThreadRunStepCancelledValue = "thread.run.step.cancelled"; + private const string ThreadRunStepExpiredValue = "thread.run.step.expired"; + private const string ThreadMessageCreatedValue = "thread.message.created"; + private const string ThreadMessageInProgressValue = "thread.message.in_progress"; + private const string ThreadMessageDeltaValue = "thread.message.delta"; + private const string ThreadMessageCompletedValue = "thread.message.completed"; + private const string ThreadMessageIncompleteValue = "thread.message.incomplete"; + private const string ErrorValue = "error"; + private const string DoneValue = "done"; + + /// Event sent when a new thread is created. The data of this event is of type AssistantThread. + public static AssistantStreamEvent ThreadCreated { get; } = new AssistantStreamEvent(ThreadCreatedValue); + /// Event sent when a new run is created. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCreated { get; } = new AssistantStreamEvent(ThreadRunCreatedValue); + /// Event sent when a run moves to `queued` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunQueued { get; } = new AssistantStreamEvent(ThreadRunQueuedValue); + /// Event sent when a run moves to `in_progress` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunInProgress { get; } = new AssistantStreamEvent(ThreadRunInProgressValue); + /// Event sent when a run moves to `requires_action` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunRequiresAction { get; } = new AssistantStreamEvent(ThreadRunRequiresActionValue); + /// Event sent when a run is completed. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCompleted { get; } = new AssistantStreamEvent(ThreadRunCompletedValue); + /// Event sent when a run fails. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunFailed { get; } = new AssistantStreamEvent(ThreadRunFailedValue); + /// Event sent when a run moves to `cancelling` status. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCancelling { get; } = new AssistantStreamEvent(ThreadRunCancellingValue); + /// Event sent when a run is cancelled. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunCancelled { get; } = new AssistantStreamEvent(ThreadRunCancelledValue); + /// Event sent when a run is expired. The data of this event is of type ThreadRun. + public static AssistantStreamEvent ThreadRunExpired { get; } = new AssistantStreamEvent(ThreadRunExpiredValue); + /// Event sent when a new thread run step is created. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepCreated { get; } = new AssistantStreamEvent(ThreadRunStepCreatedValue); + /// Event sent when a run step moves to `in_progress` status. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepInProgress { get; } = new AssistantStreamEvent(ThreadRunStepInProgressValue); + /// Event sent when a run stepis being streamed. The data of this event is of type RunStepDeltaChunk. + public static AssistantStreamEvent ThreadRunStepDelta { get; } = new AssistantStreamEvent(ThreadRunStepDeltaValue); + /// Event sent when a run step is completed. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepCompleted { get; } = new AssistantStreamEvent(ThreadRunStepCompletedValue); + /// Event sent when a run step fails. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepFailed { get; } = new AssistantStreamEvent(ThreadRunStepFailedValue); + /// Event sent when a run step is cancelled. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepCancelled { get; } = new AssistantStreamEvent(ThreadRunStepCancelledValue); + /// Event sent when a run step is expired. The data of this event is of type RunStep. + public static AssistantStreamEvent ThreadRunStepExpired { get; } = new AssistantStreamEvent(ThreadRunStepExpiredValue); + /// Event sent when a new message is created. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageCreated { get; } = new AssistantStreamEvent(ThreadMessageCreatedValue); + /// Event sent when a message moves to `in_progress` status. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageInProgress { get; } = new AssistantStreamEvent(ThreadMessageInProgressValue); + /// Event sent when a message is being streamed. The data of this event is of type MessageDeltaChunk. + public static AssistantStreamEvent ThreadMessageDelta { get; } = new AssistantStreamEvent(ThreadMessageDeltaValue); + /// Event sent when a message is completed. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageCompleted { get; } = new AssistantStreamEvent(ThreadMessageCompletedValue); + /// Event sent before a message is completed. The data of this event is of type ThreadMessage. + public static AssistantStreamEvent ThreadMessageIncomplete { get; } = new AssistantStreamEvent(ThreadMessageIncompleteValue); + /// Event sent when an error occurs, such as an internal server error or a timeout. + public static AssistantStreamEvent Error { get; } = new AssistantStreamEvent(ErrorValue); + /// Event sent when the stream is done. + public static AssistantStreamEvent Done { get; } = new AssistantStreamEvent(DoneValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantStreamEvent left, AssistantStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantStreamEvent left, AssistantStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantStreamEvent(string value) => new AssistantStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantStreamEvent other && Equals(other); + /// + public bool Equals(AssistantStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs index 568e554f63ce..0c33c423a7cb 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.Serialization.cs @@ -40,6 +40,15 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteStringValue(Object); writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -95,6 +104,7 @@ internal static AssistantThread DeserializeAssistantThread(JsonElement element, string id = default; string @object = default; DateTimeOffset createdAt = default; + ToolResources toolResources = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -115,6 +125,16 @@ internal static AssistantThread DeserializeAssistantThread(JsonElement element, createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); continue; } + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = ToolResources.DeserializeToolResources(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -136,7 +156,13 @@ internal static AssistantThread DeserializeAssistantThread(JsonElement element, } } serializedAdditionalRawData = rawDataDictionary; - return new AssistantThread(id, @object, createdAt, metadata, serializedAdditionalRawData); + return new AssistantThread( + id, + @object, + createdAt, + toolResources, + metadata, + serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs index 55fb2ac9a88e..11820b0ed0b6 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThread.cs @@ -48,14 +48,20 @@ public partial class AssistantThread /// Initializes a new instance of . /// The identifier, which can be referenced in API endpoints. /// The Unix timestamp, in seconds, representing when this object was created. + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type + /// of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list + /// of vector store IDs. + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// is null. - internal AssistantThread(string id, DateTimeOffset createdAt, IReadOnlyDictionary metadata) + internal AssistantThread(string id, DateTimeOffset createdAt, ToolResources toolResources, IReadOnlyDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Id = id; CreatedAt = createdAt; + ToolResources = toolResources; Metadata = metadata; } @@ -63,13 +69,19 @@ internal AssistantThread(string id, DateTimeOffset createdAt, IReadOnlyDictionar /// The identifier, which can be referenced in API endpoints. /// The object type, which is always 'thread'. /// The Unix timestamp, in seconds, representing when this object was created. + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type + /// of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list + /// of vector store IDs. + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal AssistantThread(string id, string @object, DateTimeOffset createdAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal AssistantThread(string id, string @object, DateTimeOffset createdAt, ToolResources toolResources, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; CreatedAt = createdAt; + ToolResources = toolResources; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -84,6 +96,12 @@ internal AssistantThread() /// The Unix timestamp, in seconds, representing when this object was created. public DateTimeOffset CreatedAt { get; } + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type + /// of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list + /// of vector store IDs. + /// + public ToolResources ToolResources { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs index 4c346f4c5b45..14aac63b59ed 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.Serialization.cs @@ -44,6 +44,18 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } writer.WriteEndArray(); } + if (Optional.IsDefined(ToolResources)) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -99,7 +111,8 @@ internal static AssistantThreadCreationOptions DeserializeAssistantThreadCreatio { return null; } - IList messages = default; + IList messages = default; + CreateToolResourcesOptions toolResources = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -111,14 +124,24 @@ internal static AssistantThreadCreationOptions DeserializeAssistantThreadCreatio { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(ThreadInitializationMessage.DeserializeThreadInitializationMessage(item, options)); + array.Add(ThreadMessageOptions.DeserializeThreadMessageOptions(item, options)); } messages = array; continue; } + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = CreateToolResourcesOptions.DeserializeCreateToolResourcesOptions(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -139,7 +162,7 @@ internal static AssistantThreadCreationOptions DeserializeAssistantThreadCreatio } } serializedAdditionalRawData = rawDataDictionary; - return new AssistantThreadCreationOptions(messages ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new AssistantThreadCreationOptions(messages ?? new ChangeTrackingList(), toolResources, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs index 2df216a2c7e8..086af4d9dc8a 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantThreadCreationOptions.cs @@ -48,23 +48,35 @@ public partial class AssistantThreadCreationOptions /// Initializes a new instance of . public AssistantThreadCreationOptions() { - Messages = new ChangeTrackingList(); + Messages = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } /// Initializes a new instance of . /// The initial messages to associate with the new thread. + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs. + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal AssistantThreadCreationOptions(IList messages, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal AssistantThreadCreationOptions(IList messages, CreateToolResourcesOptions toolResources, IDictionary metadata, IDictionary serializedAdditionalRawData) { Messages = messages; + ToolResources = toolResources; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } /// The initial messages to associate with the new thread. - public IList Messages { get; } + public IList Messages { get; } + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs. + /// + public CreateToolResourcesOptions ToolResources { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.Serialization.cs new file mode 100644 index 000000000000..3deab8002cf1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownAssistantsApiResponseFormat))] + public partial class AssistantsApiResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Type)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.Value.ToString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AssistantsApiResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsApiResponseFormat(document.RootElement, options); + } + + internal static AssistantsApiResponseFormat DeserializeAssistantsApiResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "json_object": return AssistantsApiResponseFormatJsonObject.DeserializeAssistantsApiResponseFormatJsonObject(element, options); + case "json_schema": return AssistantsApiResponseFormatJsonSchema.DeserializeAssistantsApiResponseFormatJsonSchema(element, options); + case "text": return AssistantsApiResponseFormatText.DeserializeAssistantsApiResponseFormatText(element, options); + } + } + return UnknownAssistantsApiResponseFormat.DeserializeUnknownAssistantsApiResponseFormat(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + AssistantsApiResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AssistantsApiResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormat(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.cs new file mode 100644 index 000000000000..85723ba24c31 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormat.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// An object describing the expected output of the model. If `json_object` only `function` type `tools` are allowed to be passed to the Run. + /// If `text` the model can return text or any value needed. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class AssistantsApiResponseFormat + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected AssistantsApiResponseFormat() + { + } + + /// Initializes a new instance of . + /// Must be one of `text`, `json_object` or `json_schema` . + /// Keeps track of any properties unknown to the library. + internal AssistantsApiResponseFormat(ApiResponseFormat? type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Must be one of `text`, `json_object` or `json_schema` . + internal ApiResponseFormat? Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.Serialization.cs new file mode 100644 index 000000000000..2a0cb536541a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.Serialization.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class AssistantsApiResponseFormatJsonObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonObject)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + AssistantsApiResponseFormatJsonObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsApiResponseFormatJsonObject(document.RootElement, options); + } + + internal static AssistantsApiResponseFormatJsonObject DeserializeAssistantsApiResponseFormatJsonObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ApiResponseFormat? type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new ApiResponseFormat(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AssistantsApiResponseFormatJsonObject(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonObject)} does not support writing '{options.Format}' format."); + } + } + + AssistantsApiResponseFormatJsonObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatJsonObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new AssistantsApiResponseFormatJsonObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatJsonObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.cs new file mode 100644 index 000000000000..596e3ead3c16 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonObject.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// An object describing expected output of the model as a JSON object. + public partial class AssistantsApiResponseFormatJsonObject : AssistantsApiResponseFormat + { + /// Initializes a new instance of . + public AssistantsApiResponseFormatJsonObject() + { + Type = Assistants.ApiResponseFormat?.JsonObject; + } + + /// Initializes a new instance of . + /// Must be one of `text`, `json_object` or `json_schema` . + /// Keeps track of any properties unknown to the library. + internal AssistantsApiResponseFormatJsonObject(ApiResponseFormat? type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.Serialization.cs new file mode 100644 index 000000000000..ab75f3e95e18 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class AssistantsApiResponseFormatJsonSchema : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchema)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("json_schema"u8); + writer.WriteObjectValue(JsonSchema, options); + } + + AssistantsApiResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsApiResponseFormatJsonSchema(document.RootElement, options); + } + + internal static AssistantsApiResponseFormatJsonSchema DeserializeAssistantsApiResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AssistantsApiResponseFormatJsonSchemaJsonSchema jsonSchema = default; + ApiResponseFormat? type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("json_schema"u8)) + { + jsonSchema = AssistantsApiResponseFormatJsonSchemaJsonSchema.DeserializeAssistantsApiResponseFormatJsonSchemaJsonSchema(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new ApiResponseFormat(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AssistantsApiResponseFormatJsonSchema(type, serializedAdditionalRawData, jsonSchema); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + AssistantsApiResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new AssistantsApiResponseFormatJsonSchema FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatJsonSchema(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.cs new file mode 100644 index 000000000000..1b9f510138e2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchema.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// An object describing expected output of the model to match a JSON schema. + public partial class AssistantsApiResponseFormatJsonSchema : AssistantsApiResponseFormat + { + /// Initializes a new instance of . + /// The JSON schema that the model must output. + /// is null. + public AssistantsApiResponseFormatJsonSchema(AssistantsApiResponseFormatJsonSchemaJsonSchema jsonSchema) + { + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); + + Type = Assistants.ApiResponseFormat?.JsonSchema; + JsonSchema = jsonSchema; + } + + /// Initializes a new instance of . + /// Must be one of `text`, `json_object` or `json_schema` . + /// Keeps track of any properties unknown to the library. + /// The JSON schema that the model must output. + internal AssistantsApiResponseFormatJsonSchema(ApiResponseFormat? type, IDictionary serializedAdditionalRawData, AssistantsApiResponseFormatJsonSchemaJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + { + JsonSchema = jsonSchema; + } + + /// Initializes a new instance of for deserialization. + internal AssistantsApiResponseFormatJsonSchema() + { + } + + /// The JSON schema that the model must output. + public AssistantsApiResponseFormatJsonSchemaJsonSchema JsonSchema { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.Serialization.cs new file mode 100644 index 000000000000..3ce87ee9a38f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.Serialization.cs @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class AssistantsApiResponseFormatJsonSchemaJsonSchema : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchemaJsonSchema)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("schema"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Schema); +#else + using (JsonDocument document = JsonDocument.Parse(Schema, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Strict)) + { + writer.WritePropertyName("strict"u8); + writer.WriteBooleanValue(Strict.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AssistantsApiResponseFormatJsonSchemaJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchemaJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsApiResponseFormatJsonSchemaJsonSchema(document.RootElement, options); + } + + internal static AssistantsApiResponseFormatJsonSchemaJsonSchema DeserializeAssistantsApiResponseFormatJsonSchemaJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string description = default; + string name = default; + BinaryData schema = default; + bool? strict = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("schema"u8)) + { + schema = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("strict"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + strict = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AssistantsApiResponseFormatJsonSchemaJsonSchema(description, name, schema, strict, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchemaJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + AssistantsApiResponseFormatJsonSchemaJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatJsonSchemaJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatJsonSchemaJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AssistantsApiResponseFormatJsonSchemaJsonSchema FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatJsonSchemaJsonSchema(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.cs new file mode 100644 index 000000000000..ce281b777a78 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatJsonSchemaJsonSchema.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The AssistantsApiResponseFormatJsonSchemaJsonSchema. + public partial class AssistantsApiResponseFormatJsonSchemaJsonSchema + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// The schema for the response format, described as a JSON Schema object. + /// or is null. + public AssistantsApiResponseFormatJsonSchemaJsonSchema(string name, BinaryData schema) + { + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(schema, nameof(schema)); + + Name = name; + Schema = schema; + } + + /// Initializes a new instance of . + /// A description of what the response format is for, used by the model to determine how to respond in the format. + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// The schema for the response format, described as a JSON Schema object. + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the Structured Outputs guide. + /// Keeps track of any properties unknown to the library. + internal AssistantsApiResponseFormatJsonSchemaJsonSchema(string description, string name, BinaryData schema, bool? strict, IDictionary serializedAdditionalRawData) + { + Description = description; + Name = name; + Schema = schema; + Strict = strict; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AssistantsApiResponseFormatJsonSchemaJsonSchema() + { + } + + /// A description of what the response format is for, used by the model to determine how to respond in the format. + public string Description { get; set; } + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + public string Name { get; set; } + /// + /// The schema for the response format, described as a JSON Schema object. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Schema { get; set; } + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the Structured Outputs guide. + public bool? Strict { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatMode.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatMode.cs new file mode 100644 index 000000000000..56e7d3f9a04b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatMode.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the mode in which the model will handle the return format of a tool call. + public readonly partial struct AssistantsApiResponseFormatMode : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantsApiResponseFormatMode(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + + /// Default value. Let the model handle the return format. + public static AssistantsApiResponseFormatMode Auto { get; } = new AssistantsApiResponseFormatMode(AutoValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantsApiResponseFormatMode left, AssistantsApiResponseFormatMode right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantsApiResponseFormatMode left, AssistantsApiResponseFormatMode right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantsApiResponseFormatMode(string value) => new AssistantsApiResponseFormatMode(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantsApiResponseFormatMode other && Equals(other); + /// + public bool Equals(AssistantsApiResponseFormatMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.Serialization.cs new file mode 100644 index 000000000000..b1fc00fadf3b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.Serialization.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class AssistantsApiResponseFormatText : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatText)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + AssistantsApiResponseFormatText IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatText)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsApiResponseFormatText(document.RootElement, options); + } + + internal static AssistantsApiResponseFormatText DeserializeAssistantsApiResponseFormatText(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ApiResponseFormat? type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new ApiResponseFormat(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AssistantsApiResponseFormatText(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatText)} does not support writing '{options.Format}' format."); + } + } + + AssistantsApiResponseFormatText IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatText(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormatText)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new AssistantsApiResponseFormatText FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormatText(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.cs new file mode 100644 index 000000000000..d0a8845001f6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiResponseFormatText.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// An object describing expected output of the model as text. + public partial class AssistantsApiResponseFormatText : AssistantsApiResponseFormat + { + /// Initializes a new instance of . + public AssistantsApiResponseFormatText() + { + Type = Assistants.ApiResponseFormat?.Text; + } + + /// Initializes a new instance of . + /// Must be one of `text`, `json_object` or `json_schema` . + /// Keeps track of any properties unknown to the library. + internal AssistantsApiResponseFormatText(ApiResponseFormat? type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiToolChoiceOptionMode.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiToolChoiceOptionMode.cs new file mode 100644 index 000000000000..89f7812a7ae0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsApiToolChoiceOptionMode.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Specifies how the tool choice will be used. + public readonly partial struct AssistantsApiToolChoiceOptionMode : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantsApiToolChoiceOptionMode(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NoneValue = "none"; + private const string AutoValue = "auto"; + + /// The model will not call a function and instead generates a message. + public static AssistantsApiToolChoiceOptionMode None { get; } = new AssistantsApiToolChoiceOptionMode(NoneValue); + /// The model can pick between generating a message or calling a function. + public static AssistantsApiToolChoiceOptionMode Auto { get; } = new AssistantsApiToolChoiceOptionMode(AutoValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantsApiToolChoiceOptionMode left, AssistantsApiToolChoiceOptionMode right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantsApiToolChoiceOptionMode left, AssistantsApiToolChoiceOptionMode right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantsApiToolChoiceOptionMode(string value) => new AssistantsApiToolChoiceOptionMode(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantsApiToolChoiceOptionMode other && Equals(other); + /// + public bool Equals(AssistantsApiToolChoiceOptionMode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs index c85db38a83b6..e101178cbf3b 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClient.cs @@ -7,7 +7,6 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -39,7 +38,7 @@ protected AssistantsClient() } /// Creates a new assistant. - /// Body parameter. + /// The request details to use when creating a new assistant. /// The cancellation token to use. /// is null. public virtual async Task> CreateAssistantAsync(AssistantCreationOptions body, CancellationToken cancellationToken = default) @@ -53,7 +52,7 @@ public virtual async Task> CreateAssistantAsync(AssistantCre } /// Creates a new assistant. - /// Body parameter. + /// The request details to use when creating a new assistant. /// The cancellation token to use. /// is null. public virtual Response CreateAssistant(AssistantCreationOptions body, CancellationToken cancellationToken = default) @@ -136,7 +135,7 @@ internal virtual Response CreateAssistant(RequestContent content, RequestContext /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. internal virtual async Task> InternalGetAssistantsAsync(int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { @@ -149,7 +148,7 @@ internal virtual async Task> Int /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. internal virtual Response InternalGetAssistants(int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { @@ -176,7 +175,7 @@ internal virtual Response InternalGetAssi /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// Service returned a non-success status code. /// The response returned from the service. @@ -214,7 +213,7 @@ internal virtual async Task InternalGetAssistantsAsync(int? limit, str /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// Service returned a non-success status code. /// The response returned from the service. @@ -332,7 +331,7 @@ internal virtual Response GetAssistant(string assistantId, RequestContext contex /// Modifies an existing assistant. /// The ID of the assistant to modify. - /// Body parameter. + /// The request details to use when modifying an existing assistant. /// The cancellation token to use. /// or is null. /// is an empty string, and was expected to be non-empty. @@ -349,7 +348,7 @@ public virtual async Task> UpdateAssistantAsync(string assis /// Modifies an existing assistant. /// The ID of the assistant to modify. - /// Body parameter. + /// The request details to use when modifying an existing assistant. /// The cancellation token to use. /// or is null. /// is an empty string, and was expected to be non-empty. @@ -542,42 +541,36 @@ internal virtual Response InternalDeleteAssistant(string assistantId, RequestCon } } - /// Attaches a previously uploaded file to an assistant for use by tools that can read files. - /// The ID of the assistant to attach the file to. - /// The ID of the previously uploaded file to attach. + /// Creates a new thread. Threads contain messages and can be run by assistants. + /// The details used to create a new assistant thread. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> LinkAssistantFileAsync(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + public virtual async Task> CreateThreadAsync(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(body, nameof(body)); - CreateAssistantFileRequest createAssistantFileRequest = new CreateAssistantFileRequest(fileId, null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await LinkAssistantFileAsync(assistantId, createAssistantFileRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = await CreateThreadAsync(content, context).ConfigureAwait(false); + return Response.FromValue(AssistantThread.FromResponse(response), response); } - /// Attaches a previously uploaded file to an assistant for use by tools that can read files. - /// The ID of the assistant to attach the file to. - /// The ID of the previously uploaded file to attach. + /// Creates a new thread. Threads contain messages and can be run by assistants. + /// The details used to create a new assistant thread. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response LinkAssistantFile(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + public virtual Response CreateThread(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(body, nameof(body)); - CreateAssistantFileRequest createAssistantFileRequest = new CreateAssistantFileRequest(fileId, null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = LinkAssistantFile(assistantId, createAssistantFileRequest.ToRequestContent(), context); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = CreateThread(content, context); + return Response.FromValue(AssistantThread.FromResponse(response), response); } /// - /// [Protocol Method] Attaches a previously uploaded file to an assistant for use by tools that can read files. + /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. /// /// /// @@ -586,23 +579,20 @@ public virtual Response LinkAssistantFile(string assistantId, str /// /// /// - /// The ID of the assistant to attach the file to. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task LinkAssistantFileAsync(string assistantId, RequestContent content, RequestContext context = null) + internal virtual async Task CreateThreadAsync(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.LinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); scope.Start(); try { - using HttpMessage message = CreateLinkAssistantFileRequest(assistantId, content, context); + using HttpMessage message = CreateCreateThreadRequest(content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -613,7 +603,7 @@ internal virtual async Task LinkAssistantFileAsync(string assistantId, } /// - /// [Protocol Method] Attaches a previously uploaded file to an assistant for use by tools that can read files. + /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. /// /// /// @@ -622,23 +612,20 @@ internal virtual async Task LinkAssistantFileAsync(string assistantId, /// /// /// - /// The ID of the assistant to attach the file to. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response LinkAssistantFile(string assistantId, RequestContent content, RequestContext context = null) + internal virtual Response CreateThread(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.LinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); scope.Start(); try { - using HttpMessage message = CreateLinkAssistantFileRequest(assistantId, content, context); + using HttpMessage message = CreateCreateThreadRequest(content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -648,76 +635,59 @@ internal virtual Response LinkAssistantFile(string assistantId, RequestContent c } } - /// Gets a list of files attached to a specific assistant, as used by tools that can read files. - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Gets information about an existing thread. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetAssistantFilesAsync(string assistantId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetThreadAsync(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetAssistantFilesAsync(assistantId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfAssistantFile.FromResponse(response), response); + Response response = await GetThreadAsync(threadId, context).ConfigureAwait(false); + return Response.FromValue(AssistantThread.FromResponse(response), response); } - /// Gets a list of files attached to a specific assistant, as used by tools that can read files. - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Gets information about an existing thread. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetAssistantFiles(string assistantId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetThread(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetAssistantFiles(assistantId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfAssistantFile.FromResponse(response), response); + Response response = GetThread(threadId, context); + return Response.FromValue(AssistantThread.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of files attached to a specific assistant, as used by tools that can read files. + /// [Protocol Method] Gets information about an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetAssistantFilesAsync(string assistantId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task GetThreadAsync(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetAssistantFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); scope.Start(); try { - using HttpMessage message = CreateInternalGetAssistantFilesRequest(assistantId, limit, order, after, before, context); + using HttpMessage message = CreateGetThreadRequest(threadId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -728,39 +698,30 @@ internal virtual async Task InternalGetAssistantFilesAsync(string assi } /// - /// [Protocol Method] Gets a list of files attached to a specific assistant, as used by tools that can read files. + /// [Protocol Method] Gets information about an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the assistant to retrieve the list of attached files for. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetAssistantFiles(string assistantId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response GetThread(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetAssistantFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); scope.Start(); try { - using HttpMessage message = CreateInternalGetAssistantFilesRequest(assistantId, limit, order, after, before, context); + using HttpMessage message = CreateGetThreadRequest(threadId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -770,40 +731,42 @@ internal virtual Response InternalGetAssistantFiles(string assistantId, int? lim } } - /// Retrieves a file attached to an assistant. - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// Modifies an existing thread. + /// The ID of the thread to modify. + /// The details used to update an existing assistant thread. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> GetAssistantFileAsync(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> UpdateThreadAsync(string threadId, UpdateAssistantThreadOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetAssistantFileAsync(assistantId, fileId, context).ConfigureAwait(false); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = await UpdateThreadAsync(threadId, content, context).ConfigureAwait(false); + return Response.FromValue(AssistantThread.FromResponse(response), response); } - /// Retrieves a file attached to an assistant. - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// Modifies an existing thread. + /// The ID of the thread to modify. + /// The details used to update an existing assistant thread. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response GetAssistantFile(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response UpdateThread(string threadId, UpdateAssistantThreadOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetAssistantFile(assistantId, fileId, context); - return Response.FromValue(AssistantFile.FromResponse(response), response); + Response response = UpdateThread(threadId, content, context); + return Response.FromValue(AssistantThread.FromResponse(response), response); } /// - /// [Protocol Method] Retrieves a file attached to an assistant. + /// [Protocol Method] Modifies an existing thread. /// /// /// @@ -812,23 +775,23 @@ public virtual Response GetAssistantFile(string assistantId, stri /// /// /// - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// The ID of the thread to modify. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetAssistantFileAsync(string assistantId, string fileId, RequestContext context) + internal virtual async Task UpdateThreadAsync(string threadId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); scope.Start(); try { - using HttpMessage message = CreateGetAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -839,7 +802,7 @@ internal virtual async Task GetAssistantFileAsync(string assistantId, } /// - /// [Protocol Method] Retrieves a file attached to an assistant. + /// [Protocol Method] Modifies an existing thread. /// /// /// @@ -848,23 +811,23 @@ internal virtual async Task GetAssistantFileAsync(string assistantId, /// /// /// - /// The ID of the assistant associated with the attached file. - /// The ID of the file to retrieve. + /// The ID of the thread to modify. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetAssistantFile(string assistantId, string fileId, RequestContext context) + internal virtual Response UpdateThread(string threadId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); scope.Start(); try { - using HttpMessage message = CreateGetAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -874,47 +837,36 @@ internal virtual Response GetAssistantFile(string assistantId, string fileId, Re } } - /// - /// Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. - /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// Deletes an existing thread. + /// The ID of the thread to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalUnlinkAssistantFileAsync(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual async Task> InternalDeleteThreadAsync(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalUnlinkAssistantFileAsync(assistantId, fileId, context).ConfigureAwait(false); - return Response.FromValue(InternalAssistantFileDeletionStatus.FromResponse(response), response); + Response response = await InternalDeleteThreadAsync(threadId, context).ConfigureAwait(false); + return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); } - /// - /// Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. - /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// Deletes an existing thread. + /// The ID of the thread to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual Response InternalUnlinkAssistantFile(string assistantId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual Response InternalDeleteThread(string threadId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalUnlinkAssistantFile(assistantId, fileId, context); - return Response.FromValue(InternalAssistantFileDeletionStatus.FromResponse(response), response); + Response response = InternalDeleteThread(threadId, context); + return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); } /// - /// [Protocol Method] Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. + /// [Protocol Method] Deletes an existing thread. /// /// /// @@ -923,28 +875,26 @@ internal virtual Response InternalUnlinkAss /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// The ID of the thread to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalUnlinkAssistantFileAsync(string assistantId, string fileId, RequestContext context) + internal virtual async Task InternalDeleteThreadAsync(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalUnlinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); scope.Start(); try { - using HttpMessage message = CreateInternalUnlinkAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -955,8 +905,7 @@ internal virtual async Task InternalUnlinkAssistantFileAsync(string as } /// - /// [Protocol Method] Unlinks a previously attached file from an assistant, rendering it unavailable for use by tools that can read - /// files. + /// [Protocol Method] Deletes an existing thread. /// /// /// @@ -965,28 +914,26 @@ internal virtual async Task InternalUnlinkAssistantFileAsync(string as /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the assistant from which the specified file should be unlinked. - /// The ID of the file to unlink from the specified assistant. + /// The ID of the thread to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalUnlinkAssistantFile(string assistantId, string fileId, RequestContext context) + internal virtual Response InternalDeleteThread(string threadId, RequestContext context) { - Argument.AssertNotNullOrEmpty(assistantId, nameof(assistantId)); - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalUnlinkAssistantFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); scope.Start(); try { - using HttpMessage message = CreateInternalUnlinkAssistantFileRequest(assistantId, fileId, context); + using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -996,36 +943,42 @@ internal virtual Response InternalUnlinkAssistantFile(string assistantId, string } } - /// Creates a new thread. Threads contain messages and can be run by assistants. - /// Body parameter. + /// Creates a new message on a specified thread. + /// The ID of the thread to create the new message on. + /// A single message within an assistant thread, as provided during that thread's creation for its initial state. /// The cancellation token to use. - /// is null. - public virtual async Task> CreateThreadAsync(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CreateMessageAsync(string threadId, ThreadMessageOptions body, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateThreadAsync(content, context).ConfigureAwait(false); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = await CreateMessageAsync(threadId, content, context).ConfigureAwait(false); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } - /// Creates a new thread. Threads contain messages and can be run by assistants. - /// Body parameter. + /// Creates a new message on a specified thread. + /// The ID of the thread to create the new message on. + /// A single message within an assistant thread, as provided during that thread's creation for its initial state. /// The cancellation token to use. - /// is null. - public virtual Response CreateThread(AssistantThreadCreationOptions body, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CreateMessage(string threadId, ThreadMessageOptions body, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(body, nameof(body)); using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateThread(content, context); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = CreateMessage(threadId, content, context); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. + /// [Protocol Method] Creates a new message on a specified thread. /// /// /// @@ -1034,20 +987,23 @@ public virtual Response CreateThread(AssistantThreadCreationOpt /// /// /// + /// The ID of the thread to create the new message on. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateThreadAsync(RequestContent content, RequestContext context = null) + internal virtual async Task CreateMessageAsync(string threadId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadRequest(content, context); + using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1058,7 +1014,7 @@ internal virtual async Task CreateThreadAsync(RequestContent content, } /// - /// [Protocol Method] Creates a new thread. Threads contain messages and can be run by assistants. + /// [Protocol Method] Creates a new message on a specified thread. /// /// /// @@ -1067,20 +1023,23 @@ internal virtual async Task CreateThreadAsync(RequestContent content, /// /// /// + /// The ID of the thread to create the new message on. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateThread(RequestContent content, RequestContext context = null) + internal virtual Response CreateMessage(string threadId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadRequest(content, context); + using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1090,59 +1049,79 @@ internal virtual Response CreateThread(RequestContent content, RequestContext co } } - /// Gets information about an existing thread. - /// The ID of the thread to retrieve information about. + /// Gets a list of messages that exist on a thread. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetThreadAsync(string threadId, CancellationToken cancellationToken = default) + internal virtual async Task> InternalGetMessagesAsync(string threadId, string runId = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetThreadAsync(threadId, context).ConfigureAwait(false); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = await InternalGetMessagesAsync(threadId, runId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); } - /// Gets information about an existing thread. - /// The ID of the thread to retrieve information about. + /// Gets a list of messages that exist on a thread. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - public virtual Response GetThread(string threadId, CancellationToken cancellationToken = default) + internal virtual Response InternalGetMessages(string threadId, string runId = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetThread(threadId, context); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = InternalGetMessages(threadId, runId, limit, order?.ToString(), after, before, context); + return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Gets information about an existing thread. + /// [Protocol Method] Gets a list of messages that exist on a thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// /// /// - /// The ID of the thread to retrieve information about. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetThreadAsync(string threadId, RequestContext context) + internal virtual async Task InternalGetMessagesAsync(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); scope.Start(); try { - using HttpMessage message = CreateGetThreadRequest(threadId, context); + using HttpMessage message = CreateInternalGetMessagesRequest(threadId, runId, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1153,30 +1132,40 @@ internal virtual async Task GetThreadAsync(string threadId, RequestCon } /// - /// [Protocol Method] Gets information about an existing thread. + /// [Protocol Method] Gets a list of messages that exist on a thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// /// /// - /// The ID of the thread to retrieve information about. + /// The ID of the thread to list messages from. + /// Filter messages by the run ID that generated them. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetThread(string threadId, RequestContext context) + internal virtual Response InternalGetMessages(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); scope.Start(); try { - using HttpMessage message = CreateGetThreadRequest(threadId, context); + using HttpMessage message = CreateInternalGetMessagesRequest(threadId, runId, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1186,40 +1175,40 @@ internal virtual Response GetThread(string threadId, RequestContext context) } } - /// Modifies an existing thread. - /// The ID of the thread to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Gets an existing message from an existing thread. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> UpdateThreadAsync(string threadId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetMessageAsync(string threadId, string messageId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - UpdateThreadRequest updateThreadRequest = new UpdateThreadRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UpdateThreadAsync(threadId, updateThreadRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = await GetMessageAsync(threadId, messageId, context).ConfigureAwait(false); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } - /// Modifies an existing thread. - /// The ID of the thread to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Gets an existing message from an existing thread. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response UpdateThread(string threadId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetMessage(string threadId, string messageId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - UpdateThreadRequest updateThreadRequest = new UpdateThreadRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UpdateThread(threadId, updateThreadRequest.ToRequestContent(), context); - return Response.FromValue(AssistantThread.FromResponse(response), response); + Response response = GetMessage(threadId, messageId, context); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Modifies an existing thread. + /// [Protocol Method] Gets an existing message from an existing thread. /// /// /// @@ -1228,23 +1217,23 @@ public virtual Response UpdateThread(string threadId, IReadOnly /// /// /// - /// The ID of the thread to modify. - /// The content to send as the body of the request. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UpdateThreadAsync(string threadId, RequestContent content, RequestContext context = null) + internal virtual async Task GetMessageAsync(string threadId, string messageId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); scope.Start(); try { - using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); + using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1255,7 +1244,7 @@ internal virtual async Task UpdateThreadAsync(string threadId, Request } /// - /// [Protocol Method] Modifies an existing thread. + /// [Protocol Method] Gets an existing message from an existing thread. /// /// /// @@ -1264,23 +1253,23 @@ internal virtual async Task UpdateThreadAsync(string threadId, Request /// /// /// - /// The ID of the thread to modify. - /// The content to send as the body of the request. + /// The ID of the thread to retrieve the specified message from. + /// The ID of the message to retrieve from the specified thread. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UpdateThread(string threadId, RequestContent content, RequestContext context = null) + internal virtual Response GetMessage(string threadId, string messageId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); scope.Start(); try { - using HttpMessage message = CreateUpdateThreadRequest(threadId, content, context); + using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1290,64 +1279,71 @@ internal virtual Response UpdateThread(string threadId, RequestContent content, } } - /// Deletes an existing thread. - /// The ID of the thread to delete. + /// Modifies an existing message on an existing thread. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalDeleteThreadAsync(string threadId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> UpdateMessageAsync(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalDeleteThreadAsync(threadId, context).ConfigureAwait(false); - return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); + Response response = await UpdateMessageAsync(threadId, messageId, updateMessageRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } - /// Deletes an existing thread. - /// The ID of the thread to delete. + /// Modifies an existing message on an existing thread. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalDeleteThread(string threadId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response UpdateMessage(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalDeleteThread(threadId, context); - return Response.FromValue(ThreadDeletionStatus.FromResponse(response), response); + Response response = UpdateMessage(threadId, messageId, updateMessageRequest.ToRequestContent(), context); + return Response.FromValue(ThreadMessage.FromResponse(response), response); } /// - /// [Protocol Method] Deletes an existing thread. + /// [Protocol Method] Modifies an existing message on an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to delete. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalDeleteThreadAsync(string threadId, RequestContext context) + internal virtual async Task UpdateMessageAsync(string threadId, string messageId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); + using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1358,35 +1354,34 @@ internal virtual async Task InternalDeleteThreadAsync(string threadId, } /// - /// [Protocol Method] Deletes an existing thread. + /// [Protocol Method] Modifies an existing message on an existing thread. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to delete. + /// The ID of the thread containing the specified message to modify. + /// The ID of the message to modify on the specified thread. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalDeleteThread(string threadId, RequestContext context) + internal virtual Response UpdateMessage(string threadId, string messageId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteThread"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteThreadRequest(threadId, context); + using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1396,48 +1391,44 @@ internal virtual Response InternalDeleteThread(string threadId, RequestContext c } } - /// Creates a new message on a specified thread. - /// The ID of the thread to create the new message on. - /// The role to associate with the new message. - /// The textual content for the new message. - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Creates a new run for an assistant thread. + /// The ID of the thread to run. + /// The details used when creating a new run of an assistant thread. + /// A list of additional fields to include in the response. /// The cancellation token to use. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual async Task> CreateMessageAsync(string threadId, MessageRole role, string content, IEnumerable fileIds = null, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + public virtual async Task> CreateRunAsync(string threadId, CreateRunOptions body, IEnumerable runInclude = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNull(body, nameof(body)); - CreateMessageRequest createMessageRequest = new CreateMessageRequest(role, content, fileIds?.ToList() as IReadOnlyList ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateMessageAsync(threadId, createMessageRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = await CreateRunAsync(threadId, content, runInclude, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); } - /// Creates a new message on a specified thread. - /// The ID of the thread to create the new message on. - /// The role to associate with the new message. - /// The textual content for the new message. - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Creates a new run for an assistant thread. + /// The ID of the thread to run. + /// The details used when creating a new run of an assistant thread. + /// A list of additional fields to include in the response. /// The cancellation token to use. - /// or is null. + /// or is null. /// is an empty string, and was expected to be non-empty. - public virtual Response CreateMessage(string threadId, MessageRole role, string content, IEnumerable fileIds = null, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + public virtual Response CreateRun(string threadId, CreateRunOptions body, IEnumerable runInclude = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNull(body, nameof(body)); - CreateMessageRequest createMessageRequest = new CreateMessageRequest(role, content, fileIds?.ToList() as IReadOnlyList ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateMessage(threadId, createMessageRequest.ToRequestContent(), context); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = CreateRun(threadId, content, runInclude, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Creates a new message on a specified thread. + /// [Protocol Method] Creates a new run for an assistant thread. /// /// /// @@ -1446,23 +1437,24 @@ public virtual Response CreateMessage(string threadId, MessageRol /// /// /// - /// The ID of the thread to create the new message on. + /// The ID of the thread to run. /// The content to send as the body of the request. + /// A list of additional fields to include in the response. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateMessageAsync(string threadId, RequestContent content, RequestContext context = null) + internal virtual async Task CreateRunAsync(string threadId, RequestContent content, IEnumerable runInclude = null, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); scope.Start(); try { - using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); + using HttpMessage message = CreateCreateRunRequest(threadId, content, runInclude, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1473,7 +1465,7 @@ internal virtual async Task CreateMessageAsync(string threadId, Reques } /// - /// [Protocol Method] Creates a new message on a specified thread. + /// [Protocol Method] Creates a new run for an assistant thread. /// /// /// @@ -1482,23 +1474,24 @@ internal virtual async Task CreateMessageAsync(string threadId, Reques /// /// /// - /// The ID of the thread to create the new message on. + /// The ID of the thread to run. /// The content to send as the body of the request. + /// A list of additional fields to include in the response. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// or is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateMessage(string threadId, RequestContent content, RequestContext context = null) + internal virtual Response CreateRun(string threadId, RequestContent content, IEnumerable runInclude = null, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); scope.Start(); try { - using HttpMessage message = CreateCreateMessageRequest(threadId, content, context); + using HttpMessage message = CreateCreateRunRequest(threadId, content, runInclude, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1508,44 +1501,44 @@ internal virtual Response CreateMessage(string threadId, RequestContent content, } } - /// Gets a list of messages that exist on a thread. - /// The ID of the thread to list messages from. + /// Gets a list of runs for a specified thread. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetMessagesAsync(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + internal virtual async Task> InternalGetRunsAsync(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetMessagesAsync(threadId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); + Response response = await InternalGetRunsAsync(threadId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); } - /// Gets a list of messages that exist on a thread. - /// The ID of the thread to list messages from. + /// Gets a list of runs for a specified thread. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. /// is null. /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetMessages(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + internal virtual Response InternalGetRuns(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetMessages(threadId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfThreadMessage.FromResponse(response), response); + Response response = InternalGetRuns(threadId, limit, order?.ToString(), after, before, context); + return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of messages that exist on a thread. + /// [Protocol Method] Gets a list of runs for a specified thread. /// /// /// @@ -1554,30 +1547,30 @@ internal virtual Response InternalGet /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the thread to list messages from. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetMessagesAsync(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task InternalGetRunsAsync(string threadId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessagesRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1588,7 +1581,7 @@ internal virtual async Task InternalGetMessagesAsync(string threadId, } /// - /// [Protocol Method] Gets a list of messages that exist on a thread. + /// [Protocol Method] Gets a list of runs for a specified thread. /// /// /// @@ -1597,30 +1590,30 @@ internal virtual async Task InternalGetMessagesAsync(string threadId, /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the thread to list messages from. + /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// is null. /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetMessages(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response InternalGetRuns(string threadId, int? limit, string order, string after, string before, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessages"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessagesRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1630,40 +1623,40 @@ internal virtual Response InternalGetMessages(string threadId, int? limit, strin } } - /// Gets an existing message from an existing thread. - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// Gets an existing run from an existing thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> GetMessageAsync(string threadId, string messageId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetMessageAsync(threadId, messageId, context).ConfigureAwait(false); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = await GetRunAsync(threadId, runId, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); } - /// Gets an existing message from an existing thread. - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// Gets an existing run from an existing thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response GetMessage(string threadId, string messageId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetRun(string threadId, string runId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetMessage(threadId, messageId, context); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = GetRun(threadId, runId, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Gets an existing message from an existing thread. + /// [Protocol Method] Gets an existing run from an existing thread. /// /// /// @@ -1672,23 +1665,23 @@ public virtual Response GetMessage(string threadId, string messag /// /// /// - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetMessageAsync(string threadId, string messageId, RequestContext context) + internal virtual async Task GetRunAsync(string threadId, string runId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); scope.Start(); try { - using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); + using HttpMessage message = CreateGetRunRequest(threadId, runId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1699,7 +1692,7 @@ internal virtual async Task GetMessageAsync(string threadId, string me } /// - /// [Protocol Method] Gets an existing message from an existing thread. + /// [Protocol Method] Gets an existing run from an existing thread. /// /// /// @@ -1708,23 +1701,23 @@ internal virtual async Task GetMessageAsync(string threadId, string me /// /// /// - /// The ID of the thread to retrieve the specified message from. - /// The ID of the message to retrieve from the specified thread. + /// The ID of the thread to retrieve run information from. + /// The ID of the thread to retrieve information about. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetMessage(string threadId, string messageId, RequestContext context) + internal virtual Response GetRun(string threadId, string runId, RequestContext context) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); scope.Start(); try { - using HttpMessage message = CreateGetMessageRequest(threadId, messageId, context); + using HttpMessage message = CreateGetRunRequest(threadId, runId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1734,44 +1727,44 @@ internal virtual Response GetMessage(string threadId, string messageId, RequestC } } - /// Modifies an existing message on an existing thread. - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// Modifies an existing thread run. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> UpdateMessageAsync(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> UpdateRunAsync(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); + UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UpdateMessageAsync(threadId, messageId, updateMessageRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = await UpdateRunAsync(threadId, runId, updateRunRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); } - /// Modifies an existing message on an existing thread. - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// Modifies an existing thread run. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response UpdateMessage(string threadId, string messageId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response UpdateRun(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest(metadata ?? new ChangeTrackingDictionary(), null); + UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UpdateMessage(threadId, messageId, updateMessageRequest.ToRequestContent(), context); - return Response.FromValue(ThreadMessage.FromResponse(response), response); + Response response = UpdateRun(threadId, runId, updateRunRequest.ToRequestContent(), context); + return Response.FromValue(ThreadRun.FromResponse(response), response); } /// - /// [Protocol Method] Modifies an existing message on an existing thread. + /// [Protocol Method] Modifies an existing thread run. /// /// /// @@ -1780,25 +1773,25 @@ public virtual Response UpdateMessage(string threadId, string mes /// /// /// - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UpdateMessageAsync(string threadId, string messageId, RequestContent content, RequestContext context = null) + internal virtual async Task UpdateRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); scope.Start(); try { - using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); + using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1809,7 +1802,7 @@ internal virtual async Task UpdateMessageAsync(string threadId, string } /// - /// [Protocol Method] Modifies an existing message on an existing thread. + /// [Protocol Method] Modifies an existing thread run. /// /// /// @@ -1818,25 +1811,25 @@ internal virtual async Task UpdateMessageAsync(string threadId, string /// /// /// - /// The ID of the thread containing the specified message to modify. - /// The ID of the message to modify on the specified thread. + /// The ID of the thread associated with the specified run. + /// The ID of the run to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UpdateMessage(string threadId, string messageId, RequestContent content, RequestContext context = null) + internal virtual Response UpdateRun(string threadId, string runId, RequestContent content, RequestContext context = null) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateMessage"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); scope.Start(); try { - using HttpMessage message = CreateUpdateMessageRequest(threadId, messageId, content, context); + using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1846,48 +1839,786 @@ internal virtual Response UpdateMessage(string threadId, string messageId, Reque } } - /// Gets a list of previously uploaded files associated with a message from a thread. - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// A list of tools for which the outputs are being submitted. + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetMessageFilesAsync(string threadId, string messageId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> SubmitToolOutputsToRunAsync(string threadId, string runId, IEnumerable toolOutputs, bool? stream = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + + SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), stream, null); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await SubmitToolOutputsToRunAsync(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// A list of tools for which the outputs are being submitted. + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// The cancellation token to use. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response SubmitToolOutputsToRun(string threadId, string runId, IEnumerable toolOutputs, bool? stream = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), stream, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetMessageFilesAsync(threadId, messageId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfMessageFile.FromResponse(response), response); + Response response = SubmitToolOutputsToRun(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// + /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task SubmitToolOutputsToRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); + scope.Start(); + try + { + using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the run that requires tool outputs. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response SubmitToolOutputsToRun(string threadId, string runId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); + scope.Start(); + try + { + using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Cancels a run of an in progress thread. + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> CancelRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CancelRunAsync(threadId, runId, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// Cancels a run of an in progress thread. + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response CancelRun(string threadId, string runId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CancelRun(threadId, runId, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// + /// [Protocol Method] Cancels a run of an in progress thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CancelRunAsync(string threadId, string runId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Cancels a run of an in progress thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread being run. + /// The ID of the run to cancel. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CancelRun(string threadId, string runId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Creates a new assistant thread and immediately starts a run using that new thread. + /// The details used when creating and immediately running a new assistant thread. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateThreadAndRunAsync(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateThreadAndRunAsync(content, context).ConfigureAwait(false); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// Creates a new assistant thread and immediately starts a run using that new thread. + /// The details used when creating and immediately running a new assistant thread. + /// The cancellation token to use. + /// is null. + public virtual Response CreateThreadAndRun(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateThreadAndRun(content, context); + return Response.FromValue(ThreadRun.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CreateThreadAndRunAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CreateThreadAndRun(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a single run step from a thread run. + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// A list of additional fields to include in the response. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public virtual async Task> GetRunStepAsync(string threadId, string runId, string stepId, IEnumerable runInclude = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetRunStepAsync(threadId, runId, stepId, runInclude, context).ConfigureAwait(false); + return Response.FromValue(RunStep.FromResponse(response), response); + } + + /// Gets a single run step from a thread run. + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// A list of additional fields to include in the response. + /// The cancellation token to use. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + public virtual Response GetRunStep(string threadId, string runId, string stepId, IEnumerable runInclude = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetRunStep(threadId, runId, stepId, runInclude, context); + return Response.FromValue(RunStep.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a single run step from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// A list of additional fields to include in the response. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetRunStepAsync(string threadId, string runId, string stepId, IEnumerable runInclude, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, runInclude, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a single run step from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the specific run to retrieve the step from. + /// The ID of the step to retrieve information about. + /// A list of additional fields to include in the response. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// , or is null. + /// , or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetRunStep(string threadId, string runId, string stepId, IEnumerable runInclude, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + scope.Start(); + try + { + using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, runInclude, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of run steps from a thread run. + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A list of additional fields to include in the response. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + internal virtual async Task> InternalGetRunStepsAsync(string threadId, string runId, IEnumerable runInclude = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await InternalGetRunStepsAsync(threadId, runId, runInclude, limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + } + + /// Gets a list of run steps from a thread run. + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A list of additional fields to include in the response. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The cancellation token to use. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + internal virtual Response InternalGetRunSteps(string threadId, string runId, IEnumerable runInclude = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = InternalGetRunSteps(threadId, runId, runInclude, limit, order?.ToString(), after, before, context); + return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of run steps from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A list of additional fields to include in the response. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task InternalGetRunStepsAsync(string threadId, string runId, IEnumerable runInclude, int? limit, string order, string after, string before, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, runInclude, limit, order, after, before, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of run steps from a thread run. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The ID of the thread that was run. + /// The ID of the run to list steps from. + /// A list of additional fields to include in the response. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response InternalGetRunSteps(string threadId, string runId, IEnumerable runInclude, int? limit, string order, string after, string before, RequestContext context) + { + Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); + Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, runInclude, limit, order, after, before, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + internal virtual async Task> InternalListFilesAsync(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await InternalListFilesAsync(purpose?.ToString(), context).ConfigureAwait(false); + return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + internal virtual Response InternalListFiles(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = InternalListFiles(purpose?.ToString(), context); + return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task InternalListFilesAsync(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response InternalListFiles(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Uploads a file for use by other operations. + /// The file data to upload and its purpose. + /// The cancellation token to use. + /// is null. + public virtual async Task> UploadFileAsync(UploadFileRequest file, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(file, nameof(file)); + + using MultipartFormDataRequestContent content = file.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await UploadFileAsync(content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// Uploads a file for use by other operations. + /// The file data to upload and its purpose. + /// The cancellation token to use. + /// is null. + public virtual Response UploadFile(UploadFileRequest file, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(file, nameof(file)); + + using MultipartFormDataRequestContent content = file.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = UploadFile(content, content.ContentType, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task UploadFileAsync(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response UploadFile(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Delete a previously uploaded file. + /// The ID of the file to delete. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual async Task> InternalDeleteFileAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await InternalDeleteFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); } - /// Gets a list of previously uploaded files associated with a message from a thread. - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Delete a previously uploaded file. + /// The ID of the file to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetMessageFiles(string threadId, string messageId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + internal virtual Response InternalDeleteFile(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetMessageFiles(threadId, messageId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfMessageFile.FromResponse(response), response); + Response response = InternalDeleteFile(fileId, context); + return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of previously uploaded files associated with a message from a thread. + /// [Protocol Method] Delete a previously uploaded file. /// /// /// @@ -1896,32 +2627,26 @@ internal virtual Response InternalGetMe /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the file to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetMessageFilesAsync(string threadId, string messageId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task InternalDeleteFileAsync(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessageFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessageFilesRequest(threadId, messageId, limit, order, after, before, context); + using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -1932,7 +2657,7 @@ internal virtual async Task InternalGetMessageFilesAsync(string thread } /// - /// [Protocol Method] Gets a list of previously uploaded files associated with a message from a thread. + /// [Protocol Method] Delete a previously uploaded file. /// /// /// @@ -1941,32 +2666,26 @@ internal virtual async Task InternalGetMessageFilesAsync(string thread /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// /// - /// The ID of the thread containing the message to list files from. - /// The ID of the message to list files from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the file to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetMessageFiles(string threadId, string messageId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response InternalDeleteFile(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetMessageFiles"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); scope.Start(); try { - using HttpMessage message = CreateInternalGetMessageFilesRequest(threadId, messageId, limit, order, after, before, context); + using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -1976,44 +2695,36 @@ internal virtual Response InternalGetMessageFiles(string threadId, string messag } } - /// Gets information about a file attachment to a message within a thread. - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual async Task> GetMessageFileAsync(string threadId, string messageId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetMessageFileAsync(threadId, messageId, fileId, context).ConfigureAwait(false); - return Response.FromValue(MessageFile.FromResponse(response), response); + Response response = await GetFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); } - /// Gets information about a file attachment to a message within a thread. - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual Response GetMessageFile(string threadId, string messageId, string fileId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFile(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetMessageFile(threadId, messageId, fileId, context); - return Response.FromValue(MessageFile.FromResponse(response), response); + Response response = GetFile(fileId, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); } /// - /// [Protocol Method] Gets information about a file attachment to a message within a thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2022,25 +2733,21 @@ public virtual Response GetMessageFile(string threadId, string mess /// /// /// - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetMessageFileAsync(string threadId, string messageId, string fileId, RequestContext context) + internal virtual async Task GetFileAsync(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessageFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); scope.Start(); try { - using HttpMessage message = CreateGetMessageFileRequest(threadId, messageId, fileId, context); + using HttpMessage message = CreateGetFileRequest(fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2051,7 +2758,7 @@ internal virtual async Task GetMessageFileAsync(string threadId, strin } /// - /// [Protocol Method] Gets information about a file attachment to a message within a thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2060,25 +2767,21 @@ internal virtual async Task GetMessageFileAsync(string threadId, strin /// /// /// - /// The ID of the thread containing the message to get information from. - /// The ID of the message to get information from. - /// The ID of the file to get information about. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetMessageFile(string threadId, string messageId, string fileId, RequestContext context) + internal virtual Response GetFile(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(messageId, nameof(messageId)); Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetMessageFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); scope.Start(); try { - using HttpMessage message = CreateGetMessageFileRequest(threadId, messageId, fileId, context); + using HttpMessage message = CreateGetFileRequest(fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2088,42 +2791,36 @@ internal virtual Response GetMessageFile(string threadId, string messageId, stri } } - /// Creates a new run for an assistant thread. - /// The ID of the thread to run. - /// The details for the run to create. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> CreateRunAsync(string threadId, CreateRunOptions createRunOptions, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileContentAsync(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(createRunOptions, nameof(createRunOptions)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using RequestContent content = createRunOptions.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateRunAsync(threadId, content, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await GetFileContentAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(response.Content, response); } - /// Creates a new run for an assistant thread. - /// The ID of the thread to run. - /// The details for the run to create. + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. /// The cancellation token to use. - /// or is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response CreateRun(string threadId, CreateRunOptions createRunOptions, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFileContent(string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(createRunOptions, nameof(createRunOptions)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using RequestContent content = createRunOptions.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateRun(threadId, content, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = GetFileContent(fileId, context); + return Response.FromValue(response.Content, response); } /// - /// [Protocol Method] Creates a new run for an assistant thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2132,23 +2829,21 @@ public virtual Response CreateRun(string threadId, CreateRunOptions c /// /// /// - /// The ID of the thread to run. - /// The content to send as the body of the request. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateRunAsync(string threadId, RequestContent content, RequestContext context = null) + internal virtual async Task GetFileContentAsync(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); scope.Start(); try { - using HttpMessage message = CreateCreateRunRequest(threadId, content, context); + using HttpMessage message = CreateGetFileContentRequest(fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2159,7 +2854,7 @@ internal virtual async Task CreateRunAsync(string threadId, RequestCon } /// - /// [Protocol Method] Creates a new run for an assistant thread. + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. /// /// /// @@ -2168,23 +2863,21 @@ internal virtual async Task CreateRunAsync(string threadId, RequestCon /// /// /// - /// The ID of the thread to run. - /// The content to send as the body of the request. + /// The ID of the file to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateRun(string threadId, RequestContent content, RequestContext context = null) + internal virtual Response GetFileContent(string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); scope.Start(); try { - using HttpMessage message = CreateCreateRunRequest(threadId, content, context); + using HttpMessage message = CreateGetFileContentRequest(fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2194,76 +2887,56 @@ internal virtual Response CreateRun(string threadId, RequestContent content, Req } } - /// Gets a list of runs for a specified thread. - /// The ID of the thread to list runs from. + /// Returns a list of vector stores. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetRunsAsync(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + public virtual async Task> GetVectorStoresAsync(int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetRunsAsync(threadId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); + Response response = await GetVectorStoresAsync(limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfVectorStore.FromResponse(response), response); } - /// Gets a list of runs for a specified thread. - /// The ID of the thread to list runs from. + /// Returns a list of vector stores. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetRuns(string threadId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + public virtual Response GetVectorStores(int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetRuns(threadId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfThreadRun.FromResponse(response), response); + Response response = GetVectorStores(limit, order?.ToString(), after, before, context); + return Response.FromValue(OpenAIPageableListOfVectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of runs for a specified thread. + /// [Protocol Method] Returns a list of vector stores. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetRunsAsync(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task GetVectorStoresAsync(int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStores"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoresRequest(limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2274,39 +2947,29 @@ internal virtual async Task InternalGetRunsAsync(string threadId, int? } /// - /// [Protocol Method] Gets a list of runs for a specified thread. + /// [Protocol Method] Returns a list of vector stores. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread to list runs from. /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetRuns(string threadId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response GetVectorStores(int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRuns"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStores"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunsRequest(threadId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoresRequest(limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2316,40 +2979,36 @@ internal virtual Response InternalGetRuns(string threadId, int? limit, string or } } - /// Gets an existing run from an existing thread. - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// Creates a vector store. + /// Request object for creating a vector store. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> GetRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + public virtual async Task> CreateVectorStoreAsync(VectorStoreOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetRunAsync(threadId, runId, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await CreateVectorStoreAsync(content, context).ConfigureAwait(false); + return Response.FromValue(VectorStore.FromResponse(response), response); } - /// Gets an existing run from an existing thread. - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// Creates a vector store. + /// Request object for creating a vector store. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response GetRun(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + public virtual Response CreateVectorStore(VectorStoreOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(body, nameof(body)); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetRun(threadId, runId, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = CreateVectorStore(content, context); + return Response.FromValue(VectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Gets an existing run from an existing thread. + /// [Protocol Method] Creates a vector store. /// /// /// @@ -2358,23 +3017,20 @@ public virtual Response GetRun(string threadId, string runId, Cancell /// /// /// - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetRunAsync(string threadId, string runId, RequestContext context) + internal virtual async Task CreateVectorStoreAsync(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStore"); scope.Start(); try { - using HttpMessage message = CreateGetRunRequest(threadId, runId, context); + using HttpMessage message = CreateCreateVectorStoreRequest(content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2385,7 +3041,7 @@ internal virtual async Task GetRunAsync(string threadId, string runId, } /// - /// [Protocol Method] Gets an existing run from an existing thread. + /// [Protocol Method] Creates a vector store. /// /// /// @@ -2394,23 +3050,20 @@ internal virtual async Task GetRunAsync(string threadId, string runId, /// /// /// - /// The ID of the thread to retrieve run information from. - /// The ID of the thread to retrieve information about. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetRun(string threadId, string runId, RequestContext context) + internal virtual Response CreateVectorStore(RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStore"); scope.Start(); try { - using HttpMessage message = CreateGetRunRequest(threadId, runId, context); + using HttpMessage message = CreateCreateVectorStoreRequest(content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2420,44 +3073,36 @@ internal virtual Response GetRun(string threadId, string runId, RequestContext c } } - /// Modifies an existing thread run. - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Returns the vector store object matching the specified ID. + /// The ID of the vector store to retrieve. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> UpdateRunAsync(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreAsync(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UpdateRunAsync(threadId, runId, updateRunRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await GetVectorStoreAsync(vectorStoreId, context).ConfigureAwait(false); + return Response.FromValue(VectorStore.FromResponse(response), response); } - /// Modifies an existing thread run. - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Returns the vector store object matching the specified ID. + /// The ID of the vector store to retrieve. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response UpdateRun(string threadId, string runId, IReadOnlyDictionary metadata = null, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStore(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - UpdateRunRequest updateRunRequest = new UpdateRunRequest(metadata ?? new ChangeTrackingDictionary(), null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UpdateRun(threadId, runId, updateRunRequest.ToRequestContent(), context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = GetVectorStore(vectorStoreId, context); + return Response.FromValue(VectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Modifies an existing thread run. + /// [Protocol Method] Returns the vector store object matching the specified ID. /// /// /// @@ -2466,25 +3111,21 @@ public virtual Response UpdateRun(string threadId, string runId, IRea /// /// /// - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// The content to send as the body of the request. + /// The ID of the vector store to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UpdateRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual async Task GetVectorStoreAsync(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStore"); scope.Start(); try { - using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateGetVectorStoreRequest(vectorStoreId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2495,7 +3136,7 @@ internal virtual async Task UpdateRunAsync(string threadId, string run } /// - /// [Protocol Method] Modifies an existing thread run. + /// [Protocol Method] Returns the vector store object matching the specified ID. /// /// /// @@ -2504,25 +3145,21 @@ internal virtual async Task UpdateRunAsync(string threadId, string run /// /// /// - /// The ID of the thread associated with the specified run. - /// The ID of the run to modify. - /// The content to send as the body of the request. + /// The ID of the vector store to retrieve. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UpdateRun(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual Response GetVectorStore(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UpdateRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStore"); scope.Start(); try { - using HttpMessage message = CreateUpdateRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateGetVectorStoreRequest(vectorStoreId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2532,46 +3169,42 @@ internal virtual Response UpdateRun(string threadId, string runId, RequestConten } } - /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. - /// The list of tool outputs requested by tool calls from the specified run. + /// The ID of the vector store to modify. + /// The ID of the vector store to modify. + /// Request object for updating a vector store. /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> SubmitToolOutputsToRunAsync(string threadId, string runId, IEnumerable toolOutputs, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> ModifyVectorStoreAsync(string vectorStoreId, VectorStoreUpdateOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(body, nameof(body)); - SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await SubmitToolOutputsToRunAsync(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await ModifyVectorStoreAsync(vectorStoreId, content, context).ConfigureAwait(false); + return Response.FromValue(VectorStore.FromResponse(response), response); } - /// Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. - /// The list of tool outputs requested by tool calls from the specified run. + /// The ID of the vector store to modify. + /// The ID of the vector store to modify. + /// Request object for updating a vector store. /// The cancellation token to use. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response SubmitToolOutputsToRun(string threadId, string runId, IEnumerable toolOutputs, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response ModifyVectorStore(string vectorStoreId, VectorStoreUpdateOptions body, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNull(toolOutputs, nameof(toolOutputs)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(body, nameof(body)); - SubmitToolOutputsToRunRequest submitToolOutputsToRunRequest = new SubmitToolOutputsToRunRequest(toolOutputs.ToList(), null); + using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = SubmitToolOutputsToRun(threadId, runId, submitToolOutputsToRunRequest.ToRequestContent(), context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = ModifyVectorStore(vectorStoreId, content, context); + return Response.FromValue(VectorStore.FromResponse(response), response); } /// - /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// [Protocol Method] The ID of the vector store to modify. /// /// /// @@ -2580,25 +3213,23 @@ public virtual Response SubmitToolOutputsToRun(string threadId, strin /// /// /// - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. + /// The ID of the vector store to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task SubmitToolOutputsToRunAsync(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual async Task ModifyVectorStoreAsync(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.ModifyVectorStore"); scope.Start(); try { - using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateModifyVectorStoreRequest(vectorStoreId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2609,7 +3240,7 @@ internal virtual async Task SubmitToolOutputsToRunAsync(string threadI } /// - /// [Protocol Method] Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool outputs will have a status of 'requires_action' with a required_action.type of 'submit_tool_outputs'. + /// [Protocol Method] The ID of the vector store to modify. /// /// /// @@ -2618,25 +3249,23 @@ internal virtual async Task SubmitToolOutputsToRunAsync(string threadI /// /// /// - /// The ID of the thread that was run. - /// The ID of the run that requires tool outputs. + /// The ID of the vector store to modify. /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response SubmitToolOutputsToRun(string threadId, string runId, RequestContent content, RequestContext context = null) + internal virtual Response ModifyVectorStore(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.SubmitToolOutputsToRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.ModifyVectorStore"); scope.Start(); try { - using HttpMessage message = CreateSubmitToolOutputsToRunRequest(threadId, runId, content, context); + using HttpMessage message = CreateModifyVectorStoreRequest(vectorStoreId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2646,40 +3275,36 @@ internal virtual Response SubmitToolOutputsToRun(string threadId, string runId, } } - /// Cancels a run of an in progress thread. - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// Deletes the vector store object matching the specified ID. + /// The ID of the vector store to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual async Task> CancelRunAsync(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> DeleteVectorStoreAsync(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CancelRunAsync(threadId, runId, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await DeleteVectorStoreAsync(vectorStoreId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreDeletionStatus.FromResponse(response), response); } - /// Cancels a run of an in progress thread. - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// Deletes the vector store object matching the specified ID. + /// The ID of the vector store to delete. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - public virtual Response CancelRun(string threadId, string runId, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response DeleteVectorStore(string vectorStoreId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CancelRun(threadId, runId, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = DeleteVectorStore(vectorStoreId, context); + return Response.FromValue(VectorStoreDeletionStatus.FromResponse(response), response); } /// - /// [Protocol Method] Cancels a run of an in progress thread. + /// [Protocol Method] Deletes the vector store object matching the specified ID. /// /// /// @@ -2688,23 +3313,21 @@ public virtual Response CancelRun(string threadId, string runId, Canc /// /// /// - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// The ID of the vector store to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CancelRunAsync(string threadId, string runId, RequestContext context) + internal virtual async Task DeleteVectorStoreAsync(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStore"); scope.Start(); try { - using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + using HttpMessage message = CreateDeleteVectorStoreRequest(vectorStoreId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2715,7 +3338,7 @@ internal virtual async Task CancelRunAsync(string threadId, string run } /// - /// [Protocol Method] Cancels a run of an in progress thread. + /// [Protocol Method] Deletes the vector store object matching the specified ID. /// /// /// @@ -2724,23 +3347,21 @@ internal virtual async Task CancelRunAsync(string threadId, string run /// /// /// - /// The ID of the thread being run. - /// The ID of the run to cancel. + /// The ID of the vector store to delete. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CancelRun(string threadId, string runId, RequestContext context) + internal virtual Response DeleteVectorStore(string vectorStoreId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStore"); scope.Start(); try { - using HttpMessage message = CreateCancelRunRequest(threadId, runId, context); + using HttpMessage message = CreateDeleteVectorStoreRequest(vectorStoreId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2750,36 +3371,46 @@ internal virtual Response CancelRun(string threadId, string runId, RequestContex } } - /// Creates a new assistant thread and immediately starts a run using that new thread. - /// Body parameter. + /// Returns a list of vector store files. + /// The ID of the vector store that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - public virtual async Task> CreateThreadAndRunAsync(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFilesAsync(string vectorStoreId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(body, nameof(body)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await CreateThreadAndRunAsync(content, context).ConfigureAwait(false); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = await GetVectorStoreFilesAsync(vectorStoreId, filter?.ToString(), limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } - /// Creates a new assistant thread and immediately starts a run using that new thread. - /// Body parameter. + /// Returns a list of vector store files. + /// The ID of the vector store that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - public virtual Response CreateThreadAndRun(CreateAndRunThreadOptions body, CancellationToken cancellationToken = default) + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFiles(string vectorStoreId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(body, nameof(body)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using RequestContent content = body.ToRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = CreateThreadAndRun(content, context); - return Response.FromValue(ThreadRun.FromResponse(response), response); + Response response = GetVectorStoreFiles(vectorStoreId, filter?.ToString(), limit, order?.ToString(), after, before, context); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// [Protocol Method] Returns a list of vector store files. /// /// /// @@ -2788,20 +3419,26 @@ public virtual Response CreateThreadAndRun(CreateAndRunThreadOptions /// /// /// - /// The content to send as the body of the request. + /// The ID of the vector store that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task CreateThreadAndRunAsync(RequestContent content, RequestContext context = null) + internal virtual async Task GetVectorStoreFilesAsync(string vectorStoreId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFiles"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + using HttpMessage message = CreateGetVectorStoreFilesRequest(vectorStoreId, filter, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2812,7 +3449,7 @@ internal virtual async Task CreateThreadAndRunAsync(RequestContent con } /// - /// [Protocol Method] Creates a new assistant thread and immediately starts a run using that new thread. + /// [Protocol Method] Returns a list of vector store files. /// /// /// @@ -2821,20 +3458,26 @@ internal virtual async Task CreateThreadAndRunAsync(RequestContent con /// /// /// - /// The content to send as the body of the request. + /// The ID of the vector store that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response CreateThreadAndRun(RequestContent content, RequestContext context = null) + internal virtual Response GetVectorStoreFiles(string vectorStoreId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateThreadAndRun"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFiles"); scope.Start(); try { - using HttpMessage message = CreateCreateThreadAndRunRequest(content, context); + using HttpMessage message = CreateGetVectorStoreFilesRequest(vectorStoreId, filter, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2844,44 +3487,44 @@ internal virtual Response CreateThreadAndRun(RequestContent content, RequestCont } } - /// Gets a single run step from a thread run. - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// Create a vector store file by attaching a file to a vector store. + /// The ID of the vector store for which to create a File. + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual async Task> GetRunStepAsync(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CreateVectorStoreFileAsync(string vectorStoreId, string fileId, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileId, nameof(fileId)); + CreateVectorStoreFileRequest createVectorStoreFileRequest = new CreateVectorStoreFileRequest(fileId, chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetRunStepAsync(threadId, runId, stepId, context).ConfigureAwait(false); - return Response.FromValue(RunStep.FromResponse(response), response); + Response response = await CreateVectorStoreFileAsync(vectorStoreId, createVectorStoreFileRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } - /// Gets a single run step from a thread run. - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// Create a vector store file by attaching a file to a vector store. + /// The ID of the vector store for which to create a File. + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. - public virtual Response GetRunStep(string threadId, string runId, string stepId, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CreateVectorStoreFile(string vectorStoreId, string fileId, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileId, nameof(fileId)); + CreateVectorStoreFileRequest createVectorStoreFileRequest = new CreateVectorStoreFileRequest(fileId, chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetRunStep(threadId, runId, stepId, context); - return Response.FromValue(RunStep.FromResponse(response), response); + Response response = CreateVectorStoreFile(vectorStoreId, createVectorStoreFileRequest.ToRequestContent(), context); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Gets a single run step from a thread run. + /// [Protocol Method] Create a vector store file by attaching a file to a vector store. /// /// /// @@ -2890,25 +3533,23 @@ public virtual Response GetRunStep(string threadId, string runId, strin /// /// /// - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// The ID of the vector store for which to create a File. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetRunStepAsync(string threadId, string runId, string stepId, RequestContext context) + internal virtual async Task CreateVectorStoreFileAsync(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, context); + using HttpMessage message = CreateCreateVectorStoreFileRequest(vectorStoreId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -2919,7 +3560,7 @@ internal virtual async Task GetRunStepAsync(string threadId, string ru } /// - /// [Protocol Method] Gets a single run step from a thread run. + /// [Protocol Method] Create a vector store file by attaching a file to a vector store. /// /// /// @@ -2928,25 +3569,23 @@ internal virtual async Task GetRunStepAsync(string threadId, string ru /// /// /// - /// The ID of the thread that was run. - /// The ID of the specific run to retrieve the step from. - /// The ID of the step to retrieve information about. + /// The ID of the vector store for which to create a File. + /// The content to send as the body of the request. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// , or is null. - /// , or is an empty string, and was expected to be non-empty. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetRunStep(string threadId, string runId, string stepId, RequestContext context) + internal virtual Response CreateVectorStoreFile(string vectorStoreId, RequestContent content, RequestContext context = null) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); - Argument.AssertNotNullOrEmpty(stepId, nameof(stepId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetRunStep"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateGetRunStepRequest(threadId, runId, stepId, context); + using HttpMessage message = CreateCreateVectorStoreFileRequest(vectorStoreId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -2956,82 +3595,65 @@ internal virtual Response GetRunStep(string threadId, string runId, string stepI } } - /// Gets a list of run steps from a thread run. - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Retrieves a vector store file. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalGetRunStepsAsync(string threadId, string runId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFileAsync(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalGetRunStepsAsync(threadId, runId, limit, order?.ToString(), after, before, context).ConfigureAwait(false); - return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + Response response = await GetVectorStoreFileAsync(vectorStoreId, fileId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } - /// Gets a list of run steps from a thread run. - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// Retrieves a vector store file. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The cancellation token to use. - /// or is null. - /// or is an empty string, and was expected to be non-empty. - internal virtual Response InternalGetRunSteps(string threadId, string runId, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalGetRunSteps(threadId, runId, limit, order?.ToString(), after, before, context); - return Response.FromValue(InternalOpenAIPageableListOfRunStep.FromResponse(response), response); + Response response = GetVectorStoreFile(vectorStoreId, fileId, context); + return Response.FromValue(VectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of run steps from a thread run. + /// [Protocol Method] Retrieves a vector store file. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalGetRunStepsAsync(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + internal virtual async Task GetVectorStoreFileAsync(string vectorStoreId, string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoreFileRequest(vectorStoreId, fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3042,41 +3664,32 @@ internal virtual async Task InternalGetRunStepsAsync(string threadId, } /// - /// [Protocol Method] Gets a list of run steps from a thread run. + /// [Protocol Method] Retrieves a vector store file. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the thread that was run. - /// The ID of the run to list steps from. - /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. - /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". - /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// The ID of the vector store that the file belongs to. + /// The ID of the file being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// or is null. - /// or is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalGetRunSteps(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + internal virtual Response GetVectorStoreFile(string vectorStoreId, string fileId, RequestContext context) { - Argument.AssertNotNullOrEmpty(threadId, nameof(threadId)); - Argument.AssertNotNullOrEmpty(runId, nameof(runId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalGetRunSteps"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalGetRunStepsRequest(threadId, runId, limit, order, after, before, context); + using HttpMessage message = CreateGetVectorStoreFileRequest(vectorStoreId, fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3086,52 +3699,72 @@ internal virtual Response InternalGetRunSteps(string threadId, string runId, int } } - /// Gets a list of previously uploaded files. - /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// + /// Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. + /// + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The cancellation token to use. - internal virtual async Task> InternalListFilesAsync(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> DeleteVectorStoreFileAsync(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalListFilesAsync(purpose?.ToString(), context).ConfigureAwait(false); - return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + Response response = await DeleteVectorStoreFileAsync(vectorStoreId, fileId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileDeletionStatus.FromResponse(response), response); } - /// Gets a list of previously uploaded files. - /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// + /// Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. + /// + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The cancellation token to use. - internal virtual Response InternalListFiles(OpenAIFilePurpose? purpose = null, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response DeleteVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalListFiles(purpose?.ToString(), context); - return Response.FromValue(InternalFileListResponse.FromResponse(response), response); + Response response = DeleteVectorStoreFile(vectorStoreId, fileId, context); + return Response.FromValue(VectorStoreFileDeletionStatus.FromResponse(response), response); } /// - /// [Protocol Method] Gets a list of previously uploaded files. + /// [Protocol Method] Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output". + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalListFilesAsync(string purpose, RequestContext context) + internal virtual async Task DeleteVectorStoreFileAsync(string vectorStoreId, string fileId, RequestContext context) { - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + using HttpMessage message = CreateDeleteVectorStoreFileRequest(vectorStoreId, fileId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3142,31 +3775,33 @@ internal virtual async Task InternalListFilesAsync(string purpose, Req } /// - /// [Protocol Method] Gets a list of previously uploaded files. + /// [Protocol Method] Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. + /// To delete the file, use the delete file endpoint. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output". + /// The ID of the vector store that the file belongs to. + /// The ID of the file to delete its relationship to the vector store. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalListFiles(string purpose, RequestContext context) + internal virtual Response DeleteVectorStoreFile(string vectorStoreId, string fileId, RequestContext context) { - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalListFiles"); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.DeleteVectorStoreFile"); scope.Start(); try { - using HttpMessage message = CreateInternalListFilesRequest(purpose, context); + using HttpMessage message = CreateDeleteVectorStoreFileRequest(vectorStoreId, fileId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3176,42 +3811,44 @@ internal virtual Response InternalListFiles(string purpose, RequestContext conte } } - /// Uploads a file for use by other operations. - /// The file data (not filename) to upload. - /// The intended purpose of the file. - /// A filename to associate with the uploaded data. + /// Create a vector store file batch. + /// The ID of the vector store for which to create a File Batch. + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// is null. - public virtual async Task> UploadFileAsync(Stream data, OpenAIFilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CreateVectorStoreFileBatchAsync(string vectorStoreId, IEnumerable fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileIds, nameof(fileIds)); - UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); - using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + CreateVectorStoreFileBatchRequest createVectorStoreFileBatchRequest = new CreateVectorStoreFileBatchRequest(fileIds.ToList(), chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await UploadFileAsync(content, content.ContentType, context).ConfigureAwait(false); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = await CreateVectorStoreFileBatchAsync(vectorStoreId, createVectorStoreFileBatchRequest.ToRequestContent(), context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } - /// Uploads a file for use by other operations. - /// The file data (not filename) to upload. - /// The intended purpose of the file. - /// A filename to associate with the uploaded data. + /// Create a vector store file batch. + /// The ID of the vector store for which to create a File Batch. + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. /// The cancellation token to use. - /// is null. - public virtual Response UploadFile(Stream data, OpenAIFilePurpose purpose, string filename = null, CancellationToken cancellationToken = default) + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CreateVectorStoreFileBatch(string vectorStoreId, IEnumerable fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileIds, nameof(fileIds)); - UploadFileRequest uploadFileRequest = new UploadFileRequest(data, purpose, filename, null); - using MultipartFormDataRequestContent content = uploadFileRequest.ToMultipartRequestContent(); + CreateVectorStoreFileBatchRequest createVectorStoreFileBatchRequest = new CreateVectorStoreFileBatchRequest(fileIds.ToList(), chunkingStrategy, null); RequestContext context = FromCancellationToken(cancellationToken); - Response response = UploadFile(content, content.ContentType, context); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = CreateVectorStoreFileBatch(vectorStoreId, createVectorStoreFileBatchRequest.ToRequestContent(), context); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } /// - /// [Protocol Method] Uploads a file for use by other operations. + /// [Protocol Method] Create a vector store file batch. /// /// /// @@ -3220,21 +3857,23 @@ public virtual Response UploadFile(Stream data, OpenAIFilePurpose pu /// /// /// + /// The ID of the vector store for which to create a File Batch. /// The content to send as the body of the request. - /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task UploadFileAsync(RequestContent content, string contentType, RequestContext context = null) + internal virtual async Task CreateVectorStoreFileBatchAsync(string vectorStoreId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + using HttpMessage message = CreateCreateVectorStoreFileBatchRequest(vectorStoreId, content, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3245,7 +3884,7 @@ internal virtual async Task UploadFileAsync(RequestContent content, st } /// - /// [Protocol Method] Uploads a file for use by other operations. + /// [Protocol Method] Create a vector store file batch. /// /// /// @@ -3254,21 +3893,23 @@ internal virtual async Task UploadFileAsync(RequestContent content, st /// /// /// + /// The ID of the vector store for which to create a File Batch. /// The content to send as the body of the request. - /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. + /// or is null. + /// is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response UploadFile(RequestContent content, string contentType, RequestContext context = null) + internal virtual Response CreateVectorStoreFileBatch(string vectorStoreId, RequestContent content, RequestContext context = null) { + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); Argument.AssertNotNull(content, nameof(content)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.UploadFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CreateVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + using HttpMessage message = CreateCreateVectorStoreFileBatchRequest(vectorStoreId, content, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3278,64 +3919,65 @@ internal virtual Response UploadFile(RequestContent content, string contentType, } } - /// Delete a previously uploaded file. - /// The ID of the file to delete. + /// Retrieve a vector store file batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual async Task> InternalDeleteFileAsync(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFileBatchAsync(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await InternalDeleteFileAsync(fileId, context).ConfigureAwait(false); - return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); + Response response = await GetVectorStoreFileBatchAsync(vectorStoreId, batchId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } - /// Delete a previously uploaded file. - /// The ID of the file to delete. + /// Retrieve a vector store file batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - internal virtual Response InternalDeleteFile(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = InternalDeleteFile(fileId, context); - return Response.FromValue(InternalFileDeletionStatus.FromResponse(response), response); + Response response = GetVectorStoreFileBatch(vectorStoreId, batchId, context); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } /// - /// [Protocol Method] Delete a previously uploaded file. + /// [Protocol Method] Retrieve a vector store file batch. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the file to delete. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task InternalDeleteFileAsync(string fileId, RequestContext context) + internal virtual async Task GetVectorStoreFileBatchAsync(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3346,35 +3988,32 @@ internal virtual async Task InternalDeleteFileAsync(string fileId, Req } /// - /// [Protocol Method] Delete a previously uploaded file. + /// [Protocol Method] Retrieve a vector store file batch. /// /// /// /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. /// /// - /// - /// - /// Please try the simpler convenience overload with strongly typed models first. - /// - /// /// /// - /// The ID of the file to delete. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch being retrieved. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response InternalDeleteFile(string fileId, RequestContext context) + internal virtual Response GetVectorStoreFileBatch(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.InternalDeleteFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateInternalDeleteFileRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3384,36 +4023,40 @@ internal virtual Response InternalDeleteFile(string fileId, RequestContext conte } } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> CancelVectorStoreFileBatchAsync(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetFileAsync(fileId, context).ConfigureAwait(false); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = await CancelVectorStoreFileBatchAsync(vectorStoreId, batchId, context).ConfigureAwait(false); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response GetFile(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response CancelVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetFile(fileId, context); - return Response.FromValue(OpenAIFile.FromResponse(response), response); + Response response = CancelVectorStoreFileBatch(vectorStoreId, batchId, context); + return Response.FromValue(VectorStoreFileBatch.FromResponse(response), response); } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. /// /// /// @@ -3422,21 +4065,23 @@ public virtual Response GetFile(string fileId, CancellationToken can /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetFileAsync(string fileId, RequestContext context) + internal virtual async Task CancelVectorStoreFileBatchAsync(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateGetFileRequest(fileId, context); + using HttpMessage message = CreateCancelVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3447,7 +4092,7 @@ internal virtual async Task GetFileAsync(string fileId, RequestContext } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. /// /// /// @@ -3456,21 +4101,23 @@ internal virtual async Task GetFileAsync(string fileId, RequestContext /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch to cancel. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetFile(string fileId, RequestContext context) + internal virtual Response CancelVectorStoreFileBatch(string vectorStoreId, string batchId, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFile"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.CancelVectorStoreFileBatch"); scope.Start(); try { - using HttpMessage message = CreateGetFileRequest(fileId, context); + using HttpMessage message = CreateCancelVectorStoreFileBatchRequest(vectorStoreId, batchId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3480,36 +4127,50 @@ internal virtual Response GetFile(string fileId, RequestContext context) } } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Returns a list of vector store files in a batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual async Task> GetFileContentAsync(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual async Task> GetVectorStoreFileBatchFilesAsync(string vectorStoreId, string batchId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await GetFileContentAsync(fileId, context).ConfigureAwait(false); - return Response.FromValue(response.Content, response); + Response response = await GetVectorStoreFileBatchFilesAsync(vectorStoreId, batchId, filter?.ToString(), limit, order?.ToString(), after, before, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } - /// Returns information about a specific file. Does not retrieve file content. - /// The ID of the file to retrieve. + /// Returns a list of vector store files in a batch. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The cancellation token to use. - /// is null. - /// is an empty string, and was expected to be non-empty. - public virtual Response GetFileContent(string fileId, CancellationToken cancellationToken = default) + /// or is null. + /// or is an empty string, and was expected to be non-empty. + public virtual Response GetVectorStoreFileBatchFiles(string vectorStoreId, string batchId, VectorStoreFileStatusFilter? filter = null, int? limit = null, ListSortOrder? order = null, string after = null, string before = null, CancellationToken cancellationToken = default) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); RequestContext context = FromCancellationToken(cancellationToken); - Response response = GetFileContent(fileId, context); - return Response.FromValue(response.Content, response); + Response response = GetVectorStoreFileBatchFiles(vectorStoreId, batchId, filter?.ToString(), limit, order?.ToString(), after, before, context); + return Response.FromValue(OpenAIPageableListOfVectorStoreFile.FromResponse(response), response); } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Returns a list of vector store files in a batch. /// /// /// @@ -3518,21 +4179,28 @@ public virtual Response GetFileContent(string fileId, CancellationTo /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual async Task GetFileContentAsync(string fileId, RequestContext context) + internal virtual async Task GetVectorStoreFileBatchFilesAsync(string vectorStoreId, string batchId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatchFiles"); scope.Start(); try { - using HttpMessage message = CreateGetFileContentRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchFilesRequest(vectorStoreId, batchId, filter, limit, order, after, before, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -3543,7 +4211,7 @@ internal virtual async Task GetFileContentAsync(string fileId, Request } /// - /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// [Protocol Method] Returns a list of vector store files in a batch. /// /// /// @@ -3552,21 +4220,28 @@ internal virtual async Task GetFileContentAsync(string fileId, Request /// /// /// - /// The ID of the file to retrieve. + /// The ID of the vector store that the file batch belongs to. + /// The ID of the file batch that the files belong to. + /// Filter by file status. Allowed values: "in_progress" | "completed" | "failed" | "cancelled". + /// A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. + /// Sort order by the created_at timestamp of the objects. asc for ascending order and desc for descending order. Allowed values: "asc" | "desc". + /// A cursor for use in pagination. after is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// A cursor for use in pagination. before is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. - /// is null. - /// is an empty string, and was expected to be non-empty. + /// or is null. + /// or is an empty string, and was expected to be non-empty. /// Service returned a non-success status code. /// The response returned from the service. - internal virtual Response GetFileContent(string fileId, RequestContext context) + internal virtual Response GetVectorStoreFileBatchFiles(string vectorStoreId, string batchId, string filter, int? limit, string order, string after, string before, RequestContext context) { - Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + Argument.AssertNotNullOrEmpty(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); - using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetFileContent"); + using var scope = ClientDiagnostics.CreateScope("AssistantsClient.GetVectorStoreFileBatchFiles"); scope.Start(); try { - using HttpMessage message = CreateGetFileContentRequest(fileId, context); + using HttpMessage message = CreateGetVectorStoreFileBatchFilesRequest(vectorStoreId, batchId, filter, limit, order, after, before, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -3576,6 +4251,380 @@ internal virtual Response GetFileContent(string fileId, RequestContext context) } } + internal HttpMessage CreateInternalGetMessagesRequest(string threadId, string runId, int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/messages", false); + if (runId != null) + { + uri.AppendQuery("runId", runId, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateRunRequest(string threadId, RequestContent content, IEnumerable runInclude, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs", false); + if (runInclude != null && !(runInclude is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) + { + uri.AppendQueryDelimited("include[]", runInclude, ",", true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetRunStepRequest(string threadId, string runId, string stepId, IEnumerable runInclude, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + uri.AppendPath("/steps/", false); + uri.AppendPath(stepId, true); + if (runInclude != null && !(runInclude is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) + { + uri.AppendQueryDelimited("include[]", runInclude, ",", true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateInternalGetRunStepsRequest(string threadId, string runId, IEnumerable runInclude, int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/threads/", false); + uri.AppendPath(threadId, true); + uri.AppendPath("/runs/", false); + uri.AppendPath(runId, true); + uri.AppendPath("/steps", false); + if (runInclude != null && !(runInclude is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) + { + uri.AppendQueryDelimited("include[]", runInclude, ",", true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVectorStoresRequest(int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores", false); + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVectorStoreRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetVectorStoreRequest(string vectorStoreId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateModifyVectorStoreRequest(string vectorStoreId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteVectorStoreRequest(string vectorStoreId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVectorStoreFilesRequest(string vectorStoreId, string filter, int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files", false); + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVectorStoreFileRequest(string vectorStoreId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetVectorStoreFileRequest(string vectorStoreId, string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateDeleteVectorStoreFileRequest(string vectorStoreId, string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateVectorStoreFileBatchRequest(string vectorStoreId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetVectorStoreFileBatchRequest(string vectorStoreId, string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches/", false); + uri.AppendPath(batchId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCancelVectorStoreFileBatchRequest(string vectorStoreId, string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches/", false); + uri.AppendPath(batchId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetVectorStoreFileBatchFilesRequest(string vectorStoreId, string batchId, string filter, int? limit, string order, string after, string before, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/vector_stores/", false); + uri.AppendPath(vectorStoreId, true); + uri.AppendPath("/file_batches/", false); + uri.AppendPath(batchId, true); + uri.AppendPath("/files", false); + if (filter != null) + { + uri.AppendQuery("filter", filter, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + if (order != null) + { + uri.AppendQuery("order", order, true); + } + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (before != null) + { + uri.AppendQuery("before", before, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + private static RequestContext DefaultRequestContext = new RequestContext(); internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) { diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs index a847db2052bd..1f5ea9b91e20 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsClientOptions.cs @@ -13,13 +13,23 @@ namespace Azure.AI.OpenAI.Assistants /// Client options for AssistantsClient. public partial class AssistantsClientOptions : ClientOptions { - private const ServiceVersion LatestVersion = ServiceVersion.V2024_02_15_Preview; + private const ServiceVersion LatestVersion = ServiceVersion.V2025_01_01_Preview; /// The version of the service to use. public enum ServiceVersion { /// Service version "2024-02-15-preview". V2024_02_15_Preview = 1, + /// Service version "2024-05-01-preview". + V2024_05_01_Preview = 2, + /// Service version "2024-07-01-preview". + V2024_07_01_Preview = 3, + /// Service version "2024-09-01-preview". + V2024_09_01_Preview = 4, + /// Service version "2024-10-01-preview". + V2024_10_01_Preview = 5, + /// Service version "2025-01-01-preview". + V2025_01_01_Preview = 6, } internal string Version { get; } @@ -30,6 +40,11 @@ public AssistantsClientOptions(ServiceVersion version = LatestVersion) Version = version switch { ServiceVersion.V2024_02_15_Preview => "2024-02-15-preview", + ServiceVersion.V2024_05_01_Preview => "2024-05-01-preview", + ServiceVersion.V2024_07_01_Preview => "2024-07-01-preview", + ServiceVersion.V2024_09_01_Preview => "2024-09-01-preview", + ServiceVersion.V2024_10_01_Preview => "2024-10-01-preview", + ServiceVersion.V2025_01_01_Preview => "2025-01-01-preview", _ => throw new NotSupportedException() }; } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs index 8b4620e1331e..b710ccbef03b 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsModelFactory.cs @@ -5,6 +5,7 @@ #nullable disable +using System; using System.Collections.Generic; using System.Linq; @@ -21,15 +22,28 @@ public static partial class AssistantsModelFactory /// /// The collection of tools to enable for the new assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of previously uploaded file IDs to attach to the assistant. + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` + /// tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// A new instance for mocking. - public static AssistantCreationOptions AssistantCreationOptions(string model = null, string name = null, string description = null, string instructions = null, IEnumerable tools = null, IEnumerable fileIds = null, IDictionary metadata = null) + public static AssistantCreationOptions AssistantCreationOptions(string model = null, string name = null, string description = null, string instructions = null, IEnumerable tools = null, CreateToolResourcesOptions toolResources = null, float? temperature = null, float? topP = null, BinaryData responseFormat = null, IDictionary metadata = null) { tools ??= new List(); - fileIds ??= new List(); metadata ??= new Dictionary(); return new AssistantCreationOptions( @@ -38,37 +52,94 @@ public static AssistantCreationOptions AssistantCreationOptions(string model = n description, instructions, tools?.ToList(), - fileIds?.ToList(), + toolResources, + temperature, + topP, + responseFormat, metadata, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. + /// Initializes a new instance of . + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// A new instance for mocking. - public static ThreadInitializationMessage ThreadInitializationMessage(MessageRole role = default, string content = null, IEnumerable fileIds = null, IDictionary metadata = null) + /// A new instance for mocking. + public static CreateFileSearchToolResourceVectorStoreOptions CreateFileSearchToolResourceVectorStoreOptions(IEnumerable fileIds = null, VectorStoreChunkingStrategyRequest chunkingStrategy = null, IDictionary metadata = null) { fileIds ??= new List(); metadata ??= new Dictionary(); - return new ThreadInitializationMessage(role, content, fileIds?.ToList(), metadata, serializedAdditionalRawData: null); + return new CreateFileSearchToolResourceVectorStoreOptions(fileIds?.ToList(), chunkingStrategy, metadata, serializedAdditionalRawData: null); } - /// Initializes a new instance of . - /// The object type. - /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. - /// A new instance for mocking. - public static MessageTextAnnotation MessageTextAnnotation(string type = null, string text = null, int startIndex = default, int endIndex = default) + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// A new instance for mocking. + public static VectorStoreStaticChunkingStrategyRequest VectorStoreStaticChunkingStrategyRequest(VectorStoreStaticChunkingStrategyOptions @static = null) + { + return new VectorStoreStaticChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType.Static, serializedAdditionalRawData: null, @static); + } + + /// Initializes a new instance of . + /// Resources to be used by the `code_interpreter tool` consisting of file IDs. + /// Resources to be used by the `file_search` tool consisting of vector store IDs. + /// A new instance for mocking. + public static ToolResources ToolResources(CodeInterpreterToolResource codeInterpreter = null, FileSearchToolResource fileSearch = null) + { + return new ToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// A new instance for mocking. + public static CodeInterpreterToolResource CodeInterpreterToolResource(IEnumerable fileIds = null) + { + fileIds ??= new List(); + + return new CodeInterpreterToolResource(fileIds?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The ID of the vector store attached to this assistant. There can be a maximum of 1 vector + /// store attached to the assistant. + /// + /// A new instance for mocking. + public static FileSearchToolResource FileSearchToolResource(IEnumerable vectorStoreIds = null) + { + vectorStoreIds ??= new List(); + + return new FileSearchToolResource(vectorStoreIds?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. + /// + /// + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. + /// + /// A list of files attached to the message, and the tools they should be added to. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// A new instance for mocking. + public static ThreadMessageOptions ThreadMessageOptions(MessageRole role = default, string content = null, IEnumerable attachments = null, IDictionary metadata = null) { - return new UnknownMessageTextAnnotation(type, text, startIndex, endIndex, serializedAdditionalRawData: null); + attachments ??= new List(); + metadata ??= new Dictionary(); + + return new ThreadMessageOptions(role, content, attachments?.ToList(), metadata, serializedAdditionalRawData: null); } /// Initializes a new instance of . @@ -79,15 +150,46 @@ public static MessageTextAnnotation MessageTextAnnotation(string type = null, st /// Additional instructions to append at the end of the instructions for the run. This is useful for modifying the behavior /// on a per-run basis without overriding other instructions. /// + /// Adds additional messages to the thread before creating the run. /// /// The overridden list of enabled tools that the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + /// Whether to enable parallel function calling during tool use. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort + /// to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of + /// completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// A new instance for mocking. - public static CreateRunOptions CreateRunOptions(string assistantId = null, string overrideModelName = null, string overrideInstructions = null, string additionalInstructions = null, IEnumerable overrideTools = null, IDictionary metadata = null) + public static CreateRunOptions CreateRunOptions(string assistantId = null, string overrideModelName = null, string overrideInstructions = null, string additionalInstructions = null, IEnumerable additionalMessages = null, IEnumerable overrideTools = null, bool? parallelToolCalls = null, bool? stream = null, float? temperature = null, float? topP = null, int? maxPromptTokens = null, int? maxCompletionTokens = null, TruncationObject truncationStrategy = null, BinaryData toolChoice = null, BinaryData responseFormat = null, IDictionary metadata = null) { + additionalMessages ??= new List(); overrideTools ??= new List(); metadata ??= new Dictionary(); @@ -96,7 +198,17 @@ public static CreateRunOptions CreateRunOptions(string assistantId = null, strin overrideModelName, overrideInstructions, additionalInstructions, + additionalMessages?.ToList(), overrideTools?.ToList(), + parallelToolCalls, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata, serializedAdditionalRawData: null); } @@ -119,19 +231,59 @@ public static RunError RunError(string code = null, string message = null) return new RunError(code, message, serializedAdditionalRawData: null); } + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run. + /// Number of prompt tokens used over the course of the run. + /// Total number of tokens used (prompt + completion). + /// A new instance for mocking. + public static RunCompletionUsage RunCompletionUsage(long completionTokens = default, long promptTokens = default, long totalTokens = default) + { + return new RunCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData: null); + } + /// Initializes a new instance of . /// The ID of the assistant for which the thread should be created. - /// The details used to create the new thread. + /// The details used to create the new thread. If no thread is provided, an empty one will be created. /// The overridden model that the assistant should use to run the thread. /// The overridden system instructions the assistant should use to run the thread. /// /// The overridden list of enabled tools the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + /// Whether to enable parallel function calling during tool use. + /// Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens + /// specified, the run will end with status `incomplete`. See `incomplete_details` for more info. /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// A new instance for mocking. - public static CreateAndRunThreadOptions CreateAndRunThreadOptions(string assistantId = null, AssistantThreadCreationOptions thread = null, string overrideModelName = null, string overrideInstructions = null, IEnumerable overrideTools = null, IDictionary metadata = null) + public static CreateAndRunThreadOptions CreateAndRunThreadOptions(string assistantId = null, AssistantThreadCreationOptions thread = null, string overrideModelName = null, string overrideInstructions = null, IEnumerable overrideTools = null, bool? parallelToolCalls = null, UpdateToolResourcesOptions toolResources = null, bool? stream = null, float? temperature = null, float? topP = null, int? maxPromptTokens = null, int? maxCompletionTokens = null, TruncationObject truncationStrategy = null, BinaryData toolChoice = null, BinaryData responseFormat = null, IDictionary metadata = null) { overrideTools ??= new List(); metadata ??= new Dictionary(); @@ -142,6 +294,16 @@ public static CreateAndRunThreadOptions CreateAndRunThreadOptions(string assista overrideModelName, overrideInstructions, overrideTools?.ToList(), + parallelToolCalls, + toolResources, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata, serializedAdditionalRawData: null); } @@ -166,7 +328,7 @@ public static RunStepMessageCreationReference RunStepMessageCreationReference(st /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// /// A new instance for mocking. public static RunStepToolCallDetails RunStepToolCallDetails(IEnumerable toolCalls = null) @@ -209,15 +371,37 @@ public static RunStepCodeInterpreterImageReference RunStepCodeInterpreterImageRe return new RunStepCodeInterpreterImageReference(fileId, serializedAdditionalRawData: null); } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The ID of the tool call. This ID must be referenced when you submit tool outputs. - /// The key/value pairs produced by the retrieval tool. - /// A new instance for mocking. - public static RunStepRetrievalToolCall RunStepRetrievalToolCall(string id = null, IReadOnlyDictionary retrieval = null) + /// The results of the file search. + /// A new instance for mocking. + public static RunStepFileSearchToolCall RunStepFileSearchToolCall(string id = null, IEnumerable fileSearch = null) { - retrieval ??= new Dictionary(); + fileSearch ??= new List(); - return new RunStepRetrievalToolCall("retrieval", id, serializedAdditionalRawData: null, retrieval); + return new RunStepFileSearchToolCall("file_search", id, serializedAdditionalRawData: null, fileSearch?.ToList()); + } + + /// Initializes a new instance of . + /// The ID of the file that result was found in. + /// The name of the file that result was found in. + /// The score of the result. All values must be a floating point number between 0 and 1. + /// The content of the result that was found. The content is only included if requested via the include query parameter. + /// A new instance for mocking. + public static FileSearchToolCallResult FileSearchToolCallResult(string fileId = null, string fileName = null, double score = default, IEnumerable content = null) + { + content ??= new List(); + + return new FileSearchToolCallResult(fileId, fileName, score, content?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The type of the content. + /// The text content of the file. + /// A new instance for mocking. + public static FileSearchToolCallResultContentItem FileSearchToolCallResultContentItem(FileSearchToolCallResultContentItemType? type = null, string text = null) + { + return new FileSearchToolCallResultContentItem(type, text, serializedAdditionalRawData: null); } /// Initializes a new instance of . @@ -228,5 +412,488 @@ public static RunStepError RunStepError(RunStepErrorCode code = default, string { return new RunStepError(code, message, serializedAdditionalRawData: null); } + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run step. + /// Number of prompt tokens used over the course of the run step. + /// Total number of tokens used (prompt + completion). + /// A new instance for mocking. + public static RunStepCompletionUsage RunStepCompletionUsage(long completionTokens = default, long promptTokens = default, long totalTokens = default) + { + return new RunStepCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// A new instance for mocking. + public static OpenAIPageableListOfVectorStore OpenAIPageableListOfVectorStore(OpenAIPageableListOfVectorStoreObject @object = default, IEnumerable data = null, string firstId = null, string lastId = null, bool hasMore = default) + { + data ??= new List(); + + return new OpenAIPageableListOfVectorStore( + @object, + data?.ToList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store`. + /// The Unix timestamp (in seconds) for when the vector store was created. + /// The name of the vector store. + /// The total number of bytes used by the files in the vector store. + /// Files count grouped by status processed or being processed by this vector store. + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + /// Details on when this vector store expires. + /// The Unix timestamp (in seconds) for when the vector store will expire. + /// The Unix timestamp (in seconds) for when the vector store was last active. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// A new instance for mocking. + public static VectorStore VectorStore(string id = null, VectorStoreObject @object = default, DateTimeOffset createdAt = default, string name = null, int usageBytes = default, VectorStoreFileCount fileCounts = null, VectorStoreStatus status = default, VectorStoreExpirationPolicy expiresAfter = null, DateTimeOffset? expiresAt = null, DateTimeOffset? lastActiveAt = null, IReadOnlyDictionary metadata = null) + { + metadata ??= new Dictionary(); + + return new VectorStore( + id, + @object, + createdAt, + name, + usageBytes, + fileCounts, + status, + expiresAfter, + expiresAt, + lastActiveAt, + metadata, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The number of files that are currently being processed. + /// The number of files that have been successfully processed. + /// The number of files that have failed to process. + /// The number of files that were cancelled. + /// The total number of files. + /// A new instance for mocking. + public static VectorStoreFileCount VectorStoreFileCount(int inProgress = default, int completed = default, int failed = default, int cancelled = default, int total = default) + { + return new VectorStoreFileCount( + inProgress, + completed, + failed, + cancelled, + total, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'vector_store.deleted'. + /// A new instance for mocking. + public static VectorStoreDeletionStatus VectorStoreDeletionStatus(string id = null, bool deleted = default, VectorStoreDeletionStatusObject @object = default) + { + return new VectorStoreDeletionStatus(id, deleted, @object, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// A new instance for mocking. + public static OpenAIPageableListOfVectorStoreFile OpenAIPageableListOfVectorStoreFile(OpenAIPageableListOfVectorStoreFileObject @object = default, IEnumerable data = null, string firstId = null, string lastId = null, bool hasMore = default) + { + data ??= new List(); + + return new OpenAIPageableListOfVectorStoreFile( + @object, + data?.ToList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file`. + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + /// The Unix timestamp (in seconds) for when the vector store file was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + /// The last error associated with this vector store file. Will be `null` if there are no errors. + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static VectorStoreFile VectorStoreFile(string id = null, VectorStoreFileObject @object = default, int usageBytes = default, DateTimeOffset createdAt = default, string vectorStoreId = null, VectorStoreFileStatus status = default, VectorStoreFileError lastError = null, VectorStoreChunkingStrategyResponse chunkingStrategy = null) + { + return new VectorStoreFile( + id, + @object, + usageBytes, + createdAt, + vectorStoreId, + status, + lastError, + chunkingStrategy, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// One of `server_error` or `rate_limit_exceeded`. + /// A human-readable description of the error. + /// A new instance for mocking. + public static VectorStoreFileError VectorStoreFileError(VectorStoreFileErrorCode code = default, string message = null) + { + return new VectorStoreFileError(code, message, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// A new instance for mocking. + public static VectorStoreStaticChunkingStrategyResponse VectorStoreStaticChunkingStrategyResponse(VectorStoreStaticChunkingStrategyOptions @static = null) + { + return new VectorStoreStaticChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType.Static, serializedAdditionalRawData: null, @static); + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'vector_store.deleted'. + /// A new instance for mocking. + public static VectorStoreFileDeletionStatus VectorStoreFileDeletionStatus(string id = null, bool deleted = default, VectorStoreFileDeletionStatusObject @object = default) + { + return new VectorStoreFileDeletionStatus(id, deleted, @object, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file_batch`. + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + /// Files count grouped by status processed or being processed by this vector store. + /// A new instance for mocking. + public static VectorStoreFileBatch VectorStoreFileBatch(string id = null, VectorStoreFileBatchObject @object = default, DateTimeOffset createdAt = default, string vectorStoreId = null, VectorStoreFileBatchStatus status = default, VectorStoreFileCount fileCounts = null) + { + return new VectorStoreFileBatch( + id, + @object, + createdAt, + vectorStoreId, + status, + fileCounts, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier of the message, which can be referenced in API endpoints. + /// The object type, which is always `thread.message.delta`. + /// The delta containing the fields that have changed on the Message. + /// A new instance for mocking. + public static MessageDeltaChunk MessageDeltaChunk(string id = null, MessageDeltaChunkObject @object = default, MessageDelta delta = null) + { + return new MessageDeltaChunk(id, @object, delta, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The entity that produced the message. + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static MessageDelta MessageDelta(MessageRole role = default, IEnumerable content = null) + { + content ??= new List(); + + return new MessageDelta(role, content?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// A new instance for mocking. + public static MessageDeltaContent MessageDeltaContent(int index = default, string type = null) + { + return new UnknownMessageDeltaContent(index, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The image_file data. + /// A new instance for mocking. + public static MessageDeltaImageFileContent MessageDeltaImageFileContent(int index = default, MessageDeltaImageFileContentObject imageFile = null) + { + return new MessageDeltaImageFileContent(index, "image_file", serializedAdditionalRawData: null, imageFile); + } + + /// Initializes a new instance of . + /// The file ID of the image in the message content. + /// A new instance for mocking. + public static MessageDeltaImageFileContentObject MessageDeltaImageFileContentObject(string fileId = null) + { + return new MessageDeltaImageFileContentObject(fileId, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The text content details. + /// A new instance for mocking. + public static MessageDeltaTextContentObject MessageDeltaTextContentObject(int index = default, MessageDeltaTextContent text = null) + { + return new MessageDeltaTextContentObject(index, "text", serializedAdditionalRawData: null, text); + } + + /// Initializes a new instance of . + /// The data that makes up the text. + /// + /// Annotations for the text. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static MessageDeltaTextContent MessageDeltaTextContent(string value = null, IEnumerable annotations = null) + { + annotations ??= new List(); + + return new MessageDeltaTextContent(value, annotations?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// A new instance for mocking. + public static MessageDeltaTextAnnotation MessageDeltaTextAnnotation(int index = default, string type = null) + { + return new UnknownMessageDeltaTextAnnotation(index, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The file citation information. + /// The text in the message content that needs to be replaced. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + /// A new instance for mocking. + public static MessageDeltaTextFileCitationAnnotationObject MessageDeltaTextFileCitationAnnotationObject(int index = default, MessageDeltaTextFileCitationAnnotation fileCitation = null, string text = null, int? startIndex = null, int? endIndex = null) + { + return new MessageDeltaTextFileCitationAnnotationObject( + index, + "file_citation", + serializedAdditionalRawData: null, + fileCitation, + text, + startIndex, + endIndex); + } + + /// Initializes a new instance of . + /// The ID of the specific file the citation is from. + /// The specific quote in the cited file. + /// A new instance for mocking. + public static MessageDeltaTextFileCitationAnnotation MessageDeltaTextFileCitationAnnotation(string fileId = null, string quote = null) + { + return new MessageDeltaTextFileCitationAnnotation(fileId, quote, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The file path information. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + /// The text in the message content that needs to be replaced. + /// A new instance for mocking. + public static MessageDeltaTextFilePathAnnotationObject MessageDeltaTextFilePathAnnotationObject(int index = default, MessageDeltaTextFilePathAnnotation filePath = null, int? startIndex = null, int? endIndex = null, string text = null) + { + return new MessageDeltaTextFilePathAnnotationObject( + index, + "file_path", + serializedAdditionalRawData: null, + filePath, + startIndex, + endIndex, + text); + } + + /// Initializes a new instance of . + /// The file ID for the annotation. + /// A new instance for mocking. + public static MessageDeltaTextFilePathAnnotation MessageDeltaTextFilePathAnnotation(string fileId = null) + { + return new MessageDeltaTextFilePathAnnotation(fileId, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier of the run step, which can be referenced in API endpoints. + /// The object type, which is always `thread.run.step.delta`. + /// The delta containing the fields that have changed on the run step. + /// A new instance for mocking. + public static RunStepDeltaChunk RunStepDeltaChunk(string id = null, RunStepDeltaChunkObject @object = default, RunStepDelta delta = null) + { + return new RunStepDeltaChunk(id, @object, delta, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The details of the run step. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static RunStepDelta RunStepDelta(RunStepDeltaDetail stepDetails = null) + { + return new RunStepDelta(stepDetails, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The message creation data. + /// A new instance for mocking. + public static RunStepDeltaMessageCreation RunStepDeltaMessageCreation(RunStepDeltaMessageCreationObject messageCreation = null) + { + return new RunStepDeltaMessageCreation("message_creation", serializedAdditionalRawData: null, messageCreation); + } + + /// Initializes a new instance of . + /// The ID of the newly-created message. + /// A new instance for mocking. + public static RunStepDeltaMessageCreationObject RunStepDeltaMessageCreationObject(string messageId = null) + { + return new RunStepDeltaMessageCreationObject(messageId, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The collection of tool calls for the tool call detail item. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + /// A new instance for mocking. + public static RunStepDeltaToolCallObject RunStepDeltaToolCallObject(IEnumerable toolCalls = null) + { + toolCalls ??= new List(); + + return new RunStepDeltaToolCallObject("tool_calls", serializedAdditionalRawData: null, toolCalls?.ToList()); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// A new instance for mocking. + public static RunStepDeltaToolCall RunStepDeltaToolCall(int index = default, string id = null, string type = null) + { + return new UnknownRunStepDeltaToolCall(index, id, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The function data for the tool call. + /// A new instance for mocking. + public static RunStepDeltaFunctionToolCall RunStepDeltaFunctionToolCall(int index = default, string id = null, RunStepDeltaFunction function = null) + { + return new RunStepDeltaFunctionToolCall(index, id, "function", serializedAdditionalRawData: null, function); + } + + /// Initializes a new instance of . + /// The name of the function. + /// The arguments passed to the function as input. + /// The output of the function, null if outputs have not yet been submitted. + /// A new instance for mocking. + public static RunStepDeltaFunction RunStepDeltaFunction(string name = null, string arguments = null, string output = null) + { + return new RunStepDeltaFunction(name, arguments, output, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// Reserved for future use. + /// A new instance for mocking. + public static RunStepDeltaFileSearchToolCall RunStepDeltaFileSearchToolCall(int index = default, string id = null, IReadOnlyDictionary fileSearch = null) + { + fileSearch ??= new Dictionary(); + + return new RunStepDeltaFileSearchToolCall(index, id, "file_search", serializedAdditionalRawData: null, fileSearch); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The Code Interpreter data for the tool call. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterToolCall RunStepDeltaCodeInterpreterToolCall(int index = default, string id = null, RunStepDeltaCodeInterpreterDetailItemObject codeInterpreter = null) + { + return new RunStepDeltaCodeInterpreterToolCall(index, id, "code_interpreter", serializedAdditionalRawData: null, codeInterpreter); + } + + /// Initializes a new instance of . + /// The input into the Code Interpreter tool call. + /// + /// The outputs from the Code Interpreter tool call. Code Interpreter can output one or more + /// items, including text (`logs`) or images (`image`). Each of these are represented by a + /// different object type. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterDetailItemObject RunStepDeltaCodeInterpreterDetailItemObject(string input = null, IEnumerable outputs = null) + { + outputs ??= new List(); + + return new RunStepDeltaCodeInterpreterDetailItemObject(input, outputs?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterOutput RunStepDeltaCodeInterpreterOutput(int index = default, string type = null) + { + return new UnknownRunStepDeltaCodeInterpreterOutput(index, type, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The text output from the Code Interpreter tool call. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterLogOutput RunStepDeltaCodeInterpreterLogOutput(int index = default, string logs = null) + { + return new RunStepDeltaCodeInterpreterLogOutput(index, "logs", serializedAdditionalRawData: null, logs); + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The image data for the Code Interpreter tool call output. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterImageOutput RunStepDeltaCodeInterpreterImageOutput(int index = default, RunStepDeltaCodeInterpreterImageOutputObject image = null) + { + return new RunStepDeltaCodeInterpreterImageOutput(index, "image", serializedAdditionalRawData: null, image); + } + + /// Initializes a new instance of . + /// The file ID for the image. + /// A new instance for mocking. + public static RunStepDeltaCodeInterpreterImageOutputObject RunStepDeltaCodeInterpreterImageOutputObject(string fileId = null) + { + return new RunStepDeltaCodeInterpreterImageOutputObject(fileId, serializedAdditionalRawData: null); + } } } diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.Serialization.cs similarity index 61% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.Serialization.cs index 3d4f997e8429..4c078f9fe11d 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditLivenessResponseInfo.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI.Assistants { - public partial class AuditLivenessResponseInfo : IUtf8JsonSerializable, IJsonModel + public partial class AssistantsNamedToolChoice : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,18 +28,19 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRea /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(AssistantsNamedToolChoice)} does not support writing '{format}' format."); } - writer.WritePropertyName("body"u8); - writer.WriteObjectValue(Body, options); - writer.WritePropertyName("statusCode"u8); - writer.WriteNumberValue(StatusCode); - writer.WritePropertyName("latencyInMilliseconds"u8); - writer.WriteNumberValue(LatencyInMilliseconds); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (Optional.IsDefined(Function)) + { + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -57,19 +58,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - AuditLivenessResponseInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AssistantsNamedToolChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(AssistantsNamedToolChoice)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAuditLivenessResponseInfo(document.RootElement, options); + return DeserializeAssistantsNamedToolChoice(document.RootElement, options); } - internal static AuditLivenessResponseInfo DeserializeAuditLivenessResponseInfo(JsonElement element, ModelReaderWriterOptions options = null) + internal static AssistantsNamedToolChoice DeserializeAssistantsNamedToolChoice(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -77,26 +78,24 @@ internal static AuditLivenessResponseInfo DeserializeAuditLivenessResponseInfo(J { return null; } - LivenessResponseBody body = default; - int statusCode = default; - long latencyInMilliseconds = default; + AssistantsNamedToolChoiceType type = default; + FunctionName function = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("body"u8)) + if (property.NameEquals("type"u8)) { - body = LivenessResponseBody.DeserializeLivenessResponseBody(property.Value, options); + type = new AssistantsNamedToolChoiceType(property.Value.GetString()); continue; } - if (property.NameEquals("statusCode"u8)) + if (property.NameEquals("function"u8)) { - statusCode = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("latencyInMilliseconds"u8)) - { - latencyInMilliseconds = property.Value.GetInt64(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + function = FunctionName.DeserializeFunctionName(property.Value, options); continue; } if (options.Format != "W") @@ -105,46 +104,46 @@ internal static AuditLivenessResponseInfo DeserializeAuditLivenessResponseInfo(J } } serializedAdditionalRawData = rawDataDictionary; - return new AuditLivenessResponseInfo(body, statusCode, latencyInMilliseconds, serializedAdditionalRawData); + return new AssistantsNamedToolChoice(type, function, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(AssistantsNamedToolChoice)} does not support writing '{options.Format}' format."); } } - AuditLivenessResponseInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + AssistantsNamedToolChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditLivenessResponseInfo(document.RootElement, options); + return DeserializeAssistantsNamedToolChoice(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(AuditLivenessResponseInfo)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(AssistantsNamedToolChoice)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static AuditLivenessResponseInfo FromResponse(Response response) + internal static AssistantsNamedToolChoice FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditLivenessResponseInfo(document.RootElement); + return DeserializeAssistantsNamedToolChoice(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.cs new file mode 100644 index 000000000000..b0da555fe4a1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoice.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Specifies a tool the model should use. Use to force the model to call a specific tool. + public partial class AssistantsNamedToolChoice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// the type of tool. If type is `function`, the function name must be set. + public AssistantsNamedToolChoice(AssistantsNamedToolChoiceType type) + { + Type = type; + } + + /// Initializes a new instance of . + /// the type of tool. If type is `function`, the function name must be set. + /// The name of the function to call. + /// Keeps track of any properties unknown to the library. + internal AssistantsNamedToolChoice(AssistantsNamedToolChoiceType type, FunctionName function, IDictionary serializedAdditionalRawData) + { + Type = type; + Function = function; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AssistantsNamedToolChoice() + { + } + + /// the type of tool. If type is `function`, the function name must be set. + public AssistantsNamedToolChoiceType Type { get; set; } + /// The name of the function to call. + public FunctionName Function { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoiceType.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoiceType.cs new file mode 100644 index 000000000000..0d049b86843b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantsNamedToolChoiceType.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Available tool types for assistants named tools. + public readonly partial struct AssistantsNamedToolChoiceType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AssistantsNamedToolChoiceType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FunctionValue = "function"; + private const string CodeInterpreterValue = "code_interpreter"; + private const string FileSearchValue = "file_search"; + + /// Tool type `function`. + public static AssistantsNamedToolChoiceType Function { get; } = new AssistantsNamedToolChoiceType(FunctionValue); + /// Tool type `code_interpreter`. + public static AssistantsNamedToolChoiceType CodeInterpreter { get; } = new AssistantsNamedToolChoiceType(CodeInterpreterValue); + /// Tool type `file_search`. + public static AssistantsNamedToolChoiceType FileSearch { get; } = new AssistantsNamedToolChoiceType(FileSearchValue); + /// Determines if two values are the same. + public static bool operator ==(AssistantsNamedToolChoiceType left, AssistantsNamedToolChoiceType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AssistantsNamedToolChoiceType left, AssistantsNamedToolChoiceType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AssistantsNamedToolChoiceType(string value) => new AssistantsNamedToolChoiceType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AssistantsNamedToolChoiceType other && Equals(other); + /// + public bool Equals(AssistantsNamedToolChoiceType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.Serialization.cs new file mode 100644 index 000000000000..3274271efb84 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class CodeInterpreterToolResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CodeInterpreterToolResource)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CodeInterpreterToolResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CodeInterpreterToolResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCodeInterpreterToolResource(document.RootElement, options); + } + + internal static CodeInterpreterToolResource DeserializeCodeInterpreterToolResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList fileIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CodeInterpreterToolResource(fileIds, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CodeInterpreterToolResource)} does not support writing '{options.Format}' format."); + } + } + + CodeInterpreterToolResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCodeInterpreterToolResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CodeInterpreterToolResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CodeInterpreterToolResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCodeInterpreterToolResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.cs new file mode 100644 index 000000000000..a0a185a491bc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CodeInterpreterToolResource.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of resources that are used by the `code_interpreter` tool. + public partial class CodeInterpreterToolResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// is null. + internal CodeInterpreterToolResource(IEnumerable fileIds) + { + Argument.AssertNotNull(fileIds, nameof(fileIds)); + + FileIds = fileIds.ToList(); + } + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// Keeps track of any properties unknown to the library. + internal CodeInterpreterToolResource(IReadOnlyList fileIds, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CodeInterpreterToolResource() + { + } + + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + public IReadOnlyList FileIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs index 79d6c0e271fe..18ad0dc83511 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.Serialization.cs @@ -43,23 +43,164 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } if (Optional.IsDefined(OverrideModelName)) { - writer.WritePropertyName("model"u8); - writer.WriteStringValue(OverrideModelName); + if (OverrideModelName != null) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(OverrideModelName); + } + else + { + writer.WriteNull("model"); + } } if (Optional.IsDefined(OverrideInstructions)) { - writer.WritePropertyName("instructions"u8); - writer.WriteStringValue(OverrideInstructions); + if (OverrideInstructions != null) + { + writer.WritePropertyName("instructions"u8); + writer.WriteStringValue(OverrideInstructions); + } + else + { + writer.WriteNull("instructions"); + } } if (Optional.IsCollectionDefined(OverrideTools)) { - writer.WritePropertyName("tools"u8); - writer.WriteStartArray(); - foreach (var item in OverrideTools) + if (OverrideTools != null) + { + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (var item in OverrideTools) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("tools"); + } + } + if (Optional.IsDefined(ParallelToolCalls)) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls.Value); + } + if (Optional.IsDefined(ToolResources)) + { + if (ToolResources != null) { - writer.WriteObjectValue(item, options); + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } + if (Optional.IsDefined(Stream)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(MaxPromptTokens)) + { + if (MaxPromptTokens != null) + { + writer.WritePropertyName("max_prompt_tokens"u8); + writer.WriteNumberValue(MaxPromptTokens.Value); + } + else + { + writer.WriteNull("max_prompt_tokens"); + } + } + if (Optional.IsDefined(MaxCompletionTokens)) + { + if (MaxCompletionTokens != null) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + else + { + writer.WriteNull("max_completion_tokens"); + } + } + if (Optional.IsDefined(TruncationStrategy)) + { + if (TruncationStrategy != null) + { + writer.WritePropertyName("truncation_strategy"u8); + writer.WriteObjectValue(TruncationStrategy, options); + } + else + { + writer.WriteNull("truncation_strategy"); + } + } + if (Optional.IsDefined(ToolChoice)) + { + if (ToolChoice != null) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("tool_choice"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -121,6 +262,16 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J string model = default; string instructions = default; IList tools = default; + bool? parallelToolCalls = default; + UpdateToolResourcesOptions toolResources = default; + bool? stream = default; + float? temperature = default; + float? topP = default; + int? maxPromptTokens = default; + int? maxCompletionTokens = default; + TruncationObject truncationStrategy = default; + BinaryData toolChoice = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -142,11 +293,21 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J } if (property.NameEquals("model"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + model = null; + continue; + } model = property.Value.GetString(); continue; } if (property.NameEquals("instructions"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + instructions = null; + continue; + } instructions = property.Value.GetString(); continue; } @@ -164,6 +325,104 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J tools = array; continue; } + if (property.NameEquals("parallel_tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = UpdateToolResourcesOptions.DeserializeUpdateToolResourcesOptions(property.Value, options); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("max_prompt_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxPromptTokens = null; + continue; + } + maxPromptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxCompletionTokens = null; + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("truncation_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + truncationStrategy = null; + continue; + } + truncationStrategy = TruncationObject.DeserializeTruncationObject(property.Value, options); + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolChoice = null; + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; + } + responseFormat = BinaryData.FromString(property.Value.GetRawText()); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -190,6 +449,16 @@ internal static CreateAndRunThreadOptions DeserializeCreateAndRunThreadOptions(J model, instructions, tools ?? new ChangeTrackingList(), + parallelToolCalls, + toolResources, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs index cf9c983195f7..16f117a439d8 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAndRunThreadOptions.cs @@ -59,23 +59,63 @@ public CreateAndRunThreadOptions(string assistantId) /// Initializes a new instance of . /// The ID of the assistant for which the thread should be created. - /// The details used to create the new thread. + /// The details used to create the new thread. If no thread is provided, an empty one will be created. /// The overridden model that the assistant should use to run the thread. /// The overridden system instructions the assistant should use to run the thread. /// /// The overridden list of enabled tools the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// + /// Whether to enable parallel function calling during tool use. + /// Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens + /// specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal CreateAndRunThreadOptions(string assistantId, AssistantThreadCreationOptions thread, string overrideModelName, string overrideInstructions, IList overrideTools, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal CreateAndRunThreadOptions(string assistantId, AssistantThreadCreationOptions thread, string overrideModelName, string overrideInstructions, IList overrideTools, bool? parallelToolCalls, UpdateToolResourcesOptions toolResources, bool? stream, float? temperature, float? topP, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { AssistantId = assistantId; Thread = thread; OverrideModelName = overrideModelName; OverrideInstructions = overrideInstructions; OverrideTools = overrideTools; + ParallelToolCalls = parallelToolCalls; + ToolResources = toolResources; + Stream = stream; + Temperature = temperature; + TopP = topP; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -87,7 +127,7 @@ internal CreateAndRunThreadOptions() /// The ID of the assistant for which the thread should be created. public string AssistantId { get; } - /// The details used to create the new thread. + /// The details used to create the new thread. If no thread is provided, an empty one will be created. public AssistantThreadCreationOptions Thread { get; set; } /// The overridden model that the assistant should use to run the thread. public string OverrideModelName { get; set; } @@ -96,9 +136,135 @@ internal CreateAndRunThreadOptions() /// /// The overridden list of enabled tools the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . + /// + public IList OverrideTools { get; set; } + /// Whether to enable parallel function calling during tool use. + public bool? ParallelToolCalls { get; set; } + /// Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + public UpdateToolResourcesOptions ToolResources { get; set; } + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + public bool? Stream { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxPromptTokens { get; set; } + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens + /// specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxCompletionTokens { get; set; } + /// The strategy to use for dropping messages as the context windows moves forward. + public TruncationObject TruncationStrategy { get; set; } + /// + /// Controls whether or not and which tool is called by the model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; set; } + /// + /// Specifies the format that the model must output. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// /// - public IList OverrideTools { get; } + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.Serialization.cs new file mode 100644 index 000000000000..06a1a7f3f6a6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class CreateCodeInterpreterToolResourceOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateCodeInterpreterToolResourceOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(FileIds)) + { + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CreateCodeInterpreterToolResourceOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateCodeInterpreterToolResourceOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + + internal static CreateCodeInterpreterToolResourceOptions DeserializeCreateCodeInterpreterToolResourceOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList fileIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateCodeInterpreterToolResourceOptions(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CreateCodeInterpreterToolResourceOptions)} does not support writing '{options.Format}' format."); + } + } + + CreateCodeInterpreterToolResourceOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateCodeInterpreterToolResourceOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateCodeInterpreterToolResourceOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateCodeInterpreterToolResourceOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.cs new file mode 100644 index 000000000000..97be44a94098 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateCodeInterpreterToolResourceOptions.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of resources that will be used by the `code_interpreter` tool. Request object. + public partial class CreateCodeInterpreterToolResourceOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public CreateCodeInterpreterToolResourceOptions() + { + FileIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A list of file IDs made available to the `code_interpreter` tool. + /// Keeps track of any properties unknown to the library. + internal CreateCodeInterpreterToolResourceOptions(IList fileIds, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of file IDs made available to the `code_interpreter` tool. + public IList FileIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.Serialization.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.Serialization.cs index 8bd17c2a1425..3805cd310f8f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.OpenAI.Assistants { - public partial class ThreadInitializationMessage : IUtf8JsonSerializable, IJsonModel + public partial class CreateFileSearchToolResourceVectorStoreOptions : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,26 +28,21 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ThreadInitializationMessage)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support writing '{format}' format."); } - writer.WritePropertyName("role"u8); - writer.WriteStringValue(Role.ToString()); - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content); - if (Optional.IsCollectionDefined(FileIds)) + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); + writer.WriteStringValue(item); } + writer.WriteEndArray(); + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -83,19 +78,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - ThreadInitializationMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + CreateFileSearchToolResourceVectorStoreOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(ThreadInitializationMessage)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeThreadInitializationMessage(document.RootElement, options); + return DeserializeCreateFileSearchToolResourceVectorStoreOptions(document.RootElement, options); } - internal static ThreadInitializationMessage DeserializeThreadInitializationMessage(JsonElement element, ModelReaderWriterOptions options = null) + internal static CreateFileSearchToolResourceVectorStoreOptions DeserializeCreateFileSearchToolResourceVectorStoreOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -103,30 +98,15 @@ internal static ThreadInitializationMessage DeserializeThreadInitializationMessa { return null; } - MessageRole role = default; - string content = default; IList fileIds = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("role"u8)) - { - role = new MessageRole(property.Value.GetString()); - continue; - } - if (property.NameEquals("content"u8)) - { - content = property.Value.GetString(); - continue; - } if (property.NameEquals("file_ids"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) - { - continue; - } List array = new List(); foreach (var item in property.Value.EnumerateArray()) { @@ -135,6 +115,11 @@ internal static ThreadInitializationMessage DeserializeThreadInitializationMessa fileIds = array; continue; } + if (property.NameEquals("chunking_strategy"u8)) + { + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -155,46 +140,46 @@ internal static ThreadInitializationMessage DeserializeThreadInitializationMessa } } serializedAdditionalRawData = rawDataDictionary; - return new ThreadInitializationMessage(role, content, fileIds ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new CreateFileSearchToolResourceVectorStoreOptions(fileIds, chunkingStrategy, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(ThreadInitializationMessage)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support writing '{options.Format}' format."); } } - ThreadInitializationMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + CreateFileSearchToolResourceVectorStoreOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeThreadInitializationMessage(document.RootElement, options); + return DeserializeCreateFileSearchToolResourceVectorStoreOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(ThreadInitializationMessage)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(CreateFileSearchToolResourceVectorStoreOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static ThreadInitializationMessage FromResponse(Response response) + internal static CreateFileSearchToolResourceVectorStoreOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeThreadInitializationMessage(document.RootElement); + return DeserializeCreateFileSearchToolResourceVectorStoreOptions(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.cs new file mode 100644 index 000000000000..cac5e291a8a8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateFileSearchToolResourceVectorStoreOptions.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// File IDs associated to the vector store to be passed to the helper. + public partial class CreateFileSearchToolResourceVectorStoreOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// or is null. + public CreateFileSearchToolResourceVectorStoreOptions(IEnumerable fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy) + { + Argument.AssertNotNull(fileIds, nameof(fileIds)); + Argument.AssertNotNull(chunkingStrategy, nameof(chunkingStrategy)); + + FileIds = fileIds.ToList(); + ChunkingStrategy = chunkingStrategy; + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Keeps track of any properties unknown to the library. + internal CreateFileSearchToolResourceVectorStoreOptions(IList fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary metadata, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + ChunkingStrategy = chunkingStrategy; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateFileSearchToolResourceVectorStoreOptions() + { + } + + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + public IList FileIds { get; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; } + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + public IDictionary Metadata { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs index c5d2f1cafaac..4b237e4eb15f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.Serialization.cs @@ -72,6 +72,23 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteNull("additional_instructions"); } } + if (Optional.IsCollectionDefined(AdditionalMessages)) + { + if (AdditionalMessages != null) + { + writer.WritePropertyName("additional_messages"u8); + writer.WriteStartArray(); + foreach (var item in AdditionalMessages) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("additional_messages"); + } + } if (Optional.IsCollectionDefined(OverrideTools)) { if (OverrideTools != null) @@ -89,6 +106,114 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteNull("tools"); } } + if (Optional.IsDefined(ParallelToolCalls)) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls.Value); + } + if (Optional.IsDefined(Stream)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(MaxPromptTokens)) + { + if (MaxPromptTokens != null) + { + writer.WritePropertyName("max_prompt_tokens"u8); + writer.WriteNumberValue(MaxPromptTokens.Value); + } + else + { + writer.WriteNull("max_prompt_tokens"); + } + } + if (Optional.IsDefined(MaxCompletionTokens)) + { + if (MaxCompletionTokens != null) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + else + { + writer.WriteNull("max_completion_tokens"); + } + } + if (Optional.IsDefined(TruncationStrategy)) + { + if (TruncationStrategy != null) + { + writer.WritePropertyName("truncation_strategy"u8); + writer.WriteObjectValue(TruncationStrategy, options); + } + else + { + writer.WriteNull("truncation_strategy"); + } + } + if (Optional.IsDefined(ToolChoice)) + { + if (ToolChoice != null) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("tool_choice"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); + } + } if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -148,7 +273,17 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element string model = default; string instructions = default; string additionalInstructions = default; + IList additionalMessages = default; IList tools = default; + bool? parallelToolCalls = default; + bool? stream = default; + float? temperature = default; + float? topP = default; + int? maxPromptTokens = default; + int? maxCompletionTokens = default; + TruncationObject truncationStrategy = default; + BinaryData toolChoice = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -189,6 +324,20 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element additionalInstructions = property.Value.GetString(); continue; } + if (property.NameEquals("additional_messages"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ThreadMessage.DeserializeThreadMessage(item, options)); + } + additionalMessages = array; + continue; + } if (property.NameEquals("tools"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -203,6 +352,94 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element tools = array; continue; } + if (property.NameEquals("parallel_tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("max_prompt_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxPromptTokens = null; + continue; + } + maxPromptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxCompletionTokens = null; + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("truncation_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + truncationStrategy = null; + continue; + } + truncationStrategy = TruncationObject.DeserializeTruncationObject(property.Value, options); + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolChoice = null; + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; + } + responseFormat = BinaryData.FromString(property.Value.GetRawText()); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -228,7 +465,17 @@ internal static CreateRunOptions DeserializeCreateRunOptions(JsonElement element model, instructions, additionalInstructions, + additionalMessages ?? new ChangeTrackingList(), tools ?? new ChangeTrackingList(), + parallelToolCalls, + stream, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs index 1c307b753523..b8a9e8507c50 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateRunOptions.cs @@ -53,6 +53,7 @@ public CreateRunOptions(string assistantId) Argument.AssertNotNull(assistantId, nameof(assistantId)); AssistantId = assistantId; + AdditionalMessages = new ChangeTrackingList(); OverrideTools = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } @@ -65,20 +66,60 @@ public CreateRunOptions(string assistantId) /// Additional instructions to append at the end of the instructions for the run. This is useful for modifying the behavior /// on a per-run basis without overriding other instructions. /// + /// Adds additional messages to the thread before creating the run. /// /// The overridden list of enabled tools that the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// + /// Whether to enable parallel function calling during tool use. + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort + /// to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of + /// completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Specifies the format that the model must output. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal CreateRunOptions(string assistantId, string overrideModelName, string overrideInstructions, string additionalInstructions, IList overrideTools, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal CreateRunOptions(string assistantId, string overrideModelName, string overrideInstructions, string additionalInstructions, IList additionalMessages, IList overrideTools, bool? parallelToolCalls, bool? stream, float? temperature, float? topP, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { AssistantId = assistantId; OverrideModelName = overrideModelName; OverrideInstructions = overrideInstructions; AdditionalInstructions = additionalInstructions; + AdditionalMessages = additionalMessages; OverrideTools = overrideTools; + ParallelToolCalls = parallelToolCalls; + Stream = stream; + Temperature = temperature; + TopP = topP; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -99,12 +140,138 @@ internal CreateRunOptions() /// on a per-run basis without overriding other instructions. /// public string AdditionalInstructions { get; set; } + /// Adds additional messages to the thread before creating the run. + public IList AdditionalMessages { get; set; } /// /// The overridden list of enabled tools that the assistant should use to run the thread. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IList OverrideTools { get; set; } + /// Whether to enable parallel function calling during tool use. + public bool? ParallelToolCalls { get; set; } + /// + /// If `true`, returns a stream of events that happen during the Run as server-sent events, + /// terminating when the Run enters a terminal state with a `data: [DONE]` message. + /// + public bool? Stream { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output + /// more random, while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model + /// considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens + /// comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only + /// the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, + /// the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxPromptTokens { get; set; } + /// + /// The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort + /// to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of + /// completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. + /// + public int? MaxCompletionTokens { get; set; } + /// The strategy to use for dropping messages as the context windows moves forward. + public TruncationObject TruncationStrategy { get; set; } + /// + /// Controls whether or not and which tool is called by the model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; set; } + /// + /// Specifies the format that the model must output. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.Serialization.cs new file mode 100644 index 000000000000..cad4b4ba65c7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.Serialization.cs @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class CreateToolResourcesOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateToolResourcesOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + if (Optional.IsDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(FileSearch); +#else + using (JsonDocument document = JsonDocument.Parse(FileSearch, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CreateToolResourcesOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateToolResourcesOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateToolResourcesOptions(document.RootElement, options); + } + + internal static CreateToolResourcesOptions DeserializeCreateToolResourcesOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CreateCodeInterpreterToolResourceOptions codeInterpreter = default; + BinaryData fileSearch = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = CreateCodeInterpreterToolResourceOptions.DeserializeCreateCodeInterpreterToolResourceOptions(property.Value, options); + continue; + } + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateToolResourcesOptions(codeInterpreter, fileSearch, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CreateToolResourcesOptions)} does not support writing '{options.Format}' format."); + } + } + + CreateToolResourcesOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateToolResourcesOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateToolResourcesOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateToolResourcesOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateToolResourcesOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.cs new file mode 100644 index 000000000000..796bdccc21f0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateToolResourcesOptions.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Request object. A set of resources that are used by the assistant's tools. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` + /// tool requires a list of vector store IDs. + /// + public partial class CreateToolResourcesOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public CreateToolResourcesOptions() + { + } + + /// Initializes a new instance of . + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// A list of vector stores or their IDs made available to the `file_search` tool. + /// Keeps track of any properties unknown to the library. + internal CreateToolResourcesOptions(CreateCodeInterpreterToolResourceOptions codeInterpreter, BinaryData fileSearch, IDictionary serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + FileSearch = fileSearch; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// A list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + public CreateCodeInterpreterToolResourceOptions CodeInterpreter { get; set; } + /// + /// A list of vector stores or their IDs made available to the `file_search` tool. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// where T is of type + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData FileSearch { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.Serialization.cs new file mode 100644 index 000000000000..f29ad1fbd34f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.Serialization.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class CreateVectorStoreFileBatchRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateVectorStoreFileBatchRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ChunkingStrategy)) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CreateVectorStoreFileBatchRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateVectorStoreFileBatchRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateVectorStoreFileBatchRequest(document.RootElement, options); + } + + internal static CreateVectorStoreFileBatchRequest DeserializeCreateVectorStoreFileBatchRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList fileIds = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateVectorStoreFileBatchRequest(fileIds, chunkingStrategy, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CreateVectorStoreFileBatchRequest)} does not support writing '{options.Format}' format."); + } + } + + CreateVectorStoreFileBatchRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateVectorStoreFileBatchRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateVectorStoreFileBatchRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateVectorStoreFileBatchRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateVectorStoreFileBatchRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.cs new file mode 100644 index 000000000000..ae91f3b2fed8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileBatchRequest.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The CreateVectorStoreFileBatchRequest. + internal partial class CreateVectorStoreFileBatchRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// is null. + internal CreateVectorStoreFileBatchRequest(IEnumerable fileIds) + { + Argument.AssertNotNull(fileIds, nameof(fileIds)); + + FileIds = fileIds.ToList(); + } + + /// Initializes a new instance of . + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal CreateVectorStoreFileBatchRequest(IReadOnlyList fileIds, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + ChunkingStrategy = chunkingStrategy; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateVectorStoreFileBatchRequest() + { + } + + /// A list of File IDs that the vector store should use. Useful for tools like `file_search` that can access files. + public IReadOnlyList FileIds { get; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.Serialization.cs new file mode 100644 index 000000000000..830d3de04dc3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class CreateVectorStoreFileRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateVectorStoreFileRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + if (Optional.IsDefined(ChunkingStrategy)) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CreateVectorStoreFileRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateVectorStoreFileRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateVectorStoreFileRequest(document.RootElement, options); + } + + internal static CreateVectorStoreFileRequest DeserializeCreateVectorStoreFileRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateVectorStoreFileRequest(fileId, chunkingStrategy, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CreateVectorStoreFileRequest)} does not support writing '{options.Format}' format."); + } + } + + CreateVectorStoreFileRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateVectorStoreFileRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateVectorStoreFileRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateVectorStoreFileRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateVectorStoreFileRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.cs new file mode 100644 index 000000000000..fdda0a8891d1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateVectorStoreFileRequest.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The CreateVectorStoreFileRequest. + internal partial class CreateVectorStoreFileRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// is null. + internal CreateVectorStoreFileRequest(string fileId) + { + Argument.AssertNotNull(fileId, nameof(fileId)); + + FileId = fileId; + } + + /// Initializes a new instance of . + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal CreateVectorStoreFileRequest(string fileId, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + ChunkingStrategy = chunkingStrategy; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateVectorStoreFileRequest() + { + } + + /// A File ID that the vector store should use. Useful for tools like `file_search` that can access files. + public string FileId { get; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/DoneEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/DoneEvent.cs new file mode 100644 index 000000000000..d59d8966c668 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/DoneEvent.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Terminal event indicating the successful end of a stream. + public readonly partial struct DoneEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public DoneEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string DoneValue = "done"; + + /// Event sent when the stream is done. + public static DoneEvent Done { get; } = new DoneEvent(DoneValue); + /// Determines if two values are the same. + public static bool operator ==(DoneEvent left, DoneEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(DoneEvent left, DoneEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator DoneEvent(string value) => new DoneEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is DoneEvent other && Equals(other); + /// + public bool Equals(DoneEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ErrorEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ErrorEvent.cs new file mode 100644 index 000000000000..3a26ca078a2f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ErrorEvent.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Terminal event indicating a server side error while streaming. + public readonly partial struct ErrorEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ErrorEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ErrorValue = "error"; + + /// Event sent when an error occurs, such as an internal server error or a timeout. + public static ErrorEvent Error { get; } = new ErrorEvent(ErrorValue); + /// Determines if two values are the same. + public static bool operator ==(ErrorEvent left, ErrorEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ErrorEvent left, ErrorEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ErrorEvent(string value) => new ErrorEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ErrorEvent other && Equals(other); + /// + public bool Equals(ErrorEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.Serialization.cs new file mode 100644 index 000000000000..c2034d6ebcad --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.Serialization.cs @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FileSearchToolCallResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolCallResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + writer.WritePropertyName("file_name"u8); + writer.WriteStringValue(FileName); + writer.WritePropertyName("score"u8); + writer.WriteNumberValue(Score); + if (Optional.IsCollectionDefined(Content)) + { + writer.WritePropertyName("content"u8); + writer.WriteStartArray(); + foreach (var item in Content) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FileSearchToolCallResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolCallResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileSearchToolCallResult(document.RootElement, options); + } + + internal static FileSearchToolCallResult DeserializeFileSearchToolCallResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + string fileName = default; + double score = default; + IReadOnlyList content = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("file_name"u8)) + { + fileName = property.Value.GetString(); + continue; + } + if (property.NameEquals("score"u8)) + { + score = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FileSearchToolCallResultContentItem.DeserializeFileSearchToolCallResultContentItem(item, options)); + } + content = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileSearchToolCallResult(fileId, fileName, score, content ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FileSearchToolCallResult)} does not support writing '{options.Format}' format."); + } + } + + FileSearchToolCallResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolCallResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileSearchToolCallResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileSearchToolCallResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolCallResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.cs new file mode 100644 index 000000000000..7d6159b1839f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResult.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// File search tool call result. + public partial class FileSearchToolCallResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the file that result was found in. + /// The name of the file that result was found in. + /// The score of the result. All values must be a floating point number between 0 and 1. + /// or is null. + internal FileSearchToolCallResult(string fileId, string fileName, double score) + { + Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(fileName, nameof(fileName)); + + FileId = fileId; + FileName = fileName; + Score = score; + Content = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The ID of the file that result was found in. + /// The name of the file that result was found in. + /// The score of the result. All values must be a floating point number between 0 and 1. + /// The content of the result that was found. The content is only included if requested via the include query parameter. + /// Keeps track of any properties unknown to the library. + internal FileSearchToolCallResult(string fileId, string fileName, double score, IReadOnlyList content, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + FileName = fileName; + Score = score; + Content = content; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FileSearchToolCallResult() + { + } + + /// The ID of the file that result was found in. + public string FileId { get; } + /// The name of the file that result was found in. + public string FileName { get; } + /// The score of the result. All values must be a floating point number between 0 and 1. + public double Score { get; } + /// The content of the result that was found. The content is only included if requested via the include query parameter. + public IReadOnlyList Content { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.Serialization.cs new file mode 100644 index 000000000000..0e05d7c1e915 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FileSearchToolCallResultContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolCallResultContentItem)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Type)) + { + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.Value.ToString()); + } + if (Optional.IsDefined(Text)) + { + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FileSearchToolCallResultContentItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolCallResultContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileSearchToolCallResultContentItem(document.RootElement, options); + } + + internal static FileSearchToolCallResultContentItem DeserializeFileSearchToolCallResultContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FileSearchToolCallResultContentItemType? type = default; + string text = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new FileSearchToolCallResultContentItemType(property.Value.GetString()); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileSearchToolCallResultContentItem(type, text, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FileSearchToolCallResultContentItem)} does not support writing '{options.Format}' format."); + } + } + + FileSearchToolCallResultContentItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolCallResultContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileSearchToolCallResultContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileSearchToolCallResultContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolCallResultContentItem(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.cs new file mode 100644 index 000000000000..ea20181aa787 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItem.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Content item in a file search result. + public partial class FileSearchToolCallResultContentItem + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal FileSearchToolCallResultContentItem() + { + } + + /// Initializes a new instance of . + /// The type of the content. + /// The text content of the file. + /// Keeps track of any properties unknown to the library. + internal FileSearchToolCallResultContentItem(FileSearchToolCallResultContentItemType? type, string text, IDictionary serializedAdditionalRawData) + { + Type = type; + Text = text; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The type of the content. + public FileSearchToolCallResultContentItemType? Type { get; } + /// The text content of the file. + public string Text { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItemType.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItemType.cs new file mode 100644 index 000000000000..e9a465abb4fc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolCallResultContentItemType.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The FileSearchToolCallResultContentItem_type. + public readonly partial struct FileSearchToolCallResultContentItemType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileSearchToolCallResultContentItemType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string TextValue = "text"; + + /// text. + public static FileSearchToolCallResultContentItemType Text { get; } = new FileSearchToolCallResultContentItemType(TextValue); + /// Determines if two values are the same. + public static bool operator ==(FileSearchToolCallResultContentItemType left, FileSearchToolCallResultContentItemType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileSearchToolCallResultContentItemType left, FileSearchToolCallResultContentItemType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileSearchToolCallResultContentItemType(string value) => new FileSearchToolCallResultContentItemType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileSearchToolCallResultContentItemType other && Equals(other); + /// + public bool Equals(FileSearchToolCallResultContentItemType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.Serialization.cs similarity index 60% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.Serialization.cs index b3efbd20a0e9..89ef61c42fb2 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.OpenAI.Assistants { - public partial class RunStepRetrievalToolCall : IUtf8JsonSerializable, IJsonModel + public partial class FileSearchToolDefinition : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,36 +28,33 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelRead /// The client options for reading and writing models. protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(RunStepRetrievalToolCall)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(FileSearchToolDefinition)} does not support writing '{format}' format."); } base.JsonModelWriteCore(writer, options); - writer.WritePropertyName("retrieval"u8); - writer.WriteStartObject(); - foreach (var item in Retrieval) + if (Optional.IsDefined(FileSearch)) { - writer.WritePropertyName(item.Key); - writer.WriteStringValue(item.Value); + writer.WritePropertyName("file_search"u8); + writer.WriteObjectValue(FileSearch, options); } - writer.WriteEndObject(); } - RunStepRetrievalToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + FileSearchToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(RunStepRetrievalToolCall)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(FileSearchToolDefinition)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRunStepRetrievalToolCall(document.RootElement, options); + return DeserializeFileSearchToolDefinition(document.RootElement, options); } - internal static RunStepRetrievalToolCall DeserializeRunStepRetrievalToolCall(JsonElement element, ModelReaderWriterOptions options = null) + internal static FileSearchToolDefinition DeserializeFileSearchToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -65,21 +62,19 @@ internal static RunStepRetrievalToolCall DeserializeRunStepRetrievalToolCall(Jso { return null; } - IReadOnlyDictionary retrieval = default; + FileSearchToolDefinitionDetails fileSearch = default; string type = default; - string id = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("retrieval"u8)) + if (property.NameEquals("file_search"u8)) { - Dictionary dictionary = new Dictionary(); - foreach (var property0 in property.Value.EnumerateObject()) + if (property.Value.ValueKind == JsonValueKind.Null) { - dictionary.Add(property0.Name, property0.Value.GetString()); + continue; } - retrieval = dictionary; + fileSearch = FileSearchToolDefinitionDetails.DeserializeFileSearchToolDefinitionDetails(property.Value, options); continue; } if (property.NameEquals("type"u8)) @@ -87,57 +82,52 @@ internal static RunStepRetrievalToolCall DeserializeRunStepRetrievalToolCall(Jso type = property.Value.GetString(); continue; } - if (property.NameEquals("id"u8)) - { - id = property.Value.GetString(); - continue; - } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new RunStepRetrievalToolCall(type, id, serializedAdditionalRawData, retrieval); + return new FileSearchToolDefinition(type, serializedAdditionalRawData, fileSearch); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(RunStepRetrievalToolCall)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(FileSearchToolDefinition)} does not support writing '{options.Format}' format."); } } - RunStepRetrievalToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + FileSearchToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeRunStepRetrievalToolCall(document.RootElement, options); + return DeserializeFileSearchToolDefinition(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(RunStepRetrievalToolCall)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(FileSearchToolDefinition)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static new RunStepRetrievalToolCall FromResponse(Response response) + internal static new FileSearchToolDefinition FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeRunStepRetrievalToolCall(document.RootElement); + return DeserializeFileSearchToolDefinition(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.cs new file mode 100644 index 000000000000..e68594b90832 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinition.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The input definition information for a file search tool as used to configure an assistant. + public partial class FileSearchToolDefinition : ToolDefinition + { + /// Initializes a new instance of . + public FileSearchToolDefinition() + { + Type = "file_search"; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// Options overrides for the file search tool. + internal FileSearchToolDefinition(string type, IDictionary serializedAdditionalRawData, FileSearchToolDefinitionDetails fileSearch) : base(type, serializedAdditionalRawData) + { + FileSearch = fileSearch; + } + + /// Options overrides for the file search tool. + public FileSearchToolDefinitionDetails FileSearch { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.Serialization.cs new file mode 100644 index 000000000000..eee4d45e9194 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FileSearchToolDefinitionDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolDefinitionDetails)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(MaxNumResults)) + { + writer.WritePropertyName("max_num_results"u8); + writer.WriteNumberValue(MaxNumResults.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FileSearchToolDefinitionDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolDefinitionDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileSearchToolDefinitionDetails(document.RootElement, options); + } + + internal static FileSearchToolDefinitionDetails DeserializeFileSearchToolDefinitionDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? maxNumResults = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("max_num_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxNumResults = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileSearchToolDefinitionDetails(maxNumResults, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FileSearchToolDefinitionDetails)} does not support writing '{options.Format}' format."); + } + } + + FileSearchToolDefinitionDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolDefinitionDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileSearchToolDefinitionDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileSearchToolDefinitionDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolDefinitionDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.cs new file mode 100644 index 000000000000..019548640805 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolDefinitionDetails.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Options overrides for the file search tool. + public partial class FileSearchToolDefinitionDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public FileSearchToolDefinitionDetails() + { + } + + /// Initializes a new instance of . + /// + /// The maximum number of results the file search tool should output. The default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. + /// + /// Note that the file search tool may output fewer than `max_num_results` results. See the file search tool documentation for more information. + /// + /// Keeps track of any properties unknown to the library. + internal FileSearchToolDefinitionDetails(int? maxNumResults, IDictionary serializedAdditionalRawData) + { + MaxNumResults = maxNumResults; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The maximum number of results the file search tool should output. The default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. + /// + /// Note that the file search tool may output fewer than `max_num_results` results. See the file search tool documentation for more information. + /// + public int? MaxNumResults { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.Serialization.cs new file mode 100644 index 000000000000..8957903edbe7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FileSearchToolResource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolResource)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(VectorStoreIds)) + { + writer.WritePropertyName("vector_store_ids"u8); + writer.WriteStartArray(); + foreach (var item in VectorStoreIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FileSearchToolResource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileSearchToolResource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileSearchToolResource(document.RootElement, options); + } + + internal static FileSearchToolResource DeserializeFileSearchToolResource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList vectorStoreIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("vector_store_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorStoreIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileSearchToolResource(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FileSearchToolResource)} does not support writing '{options.Format}' format."); + } + } + + FileSearchToolResource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolResource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileSearchToolResource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileSearchToolResource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileSearchToolResource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.cs new file mode 100644 index 000000000000..94422e677d08 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileSearchToolResource.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of resources that are used by the `file_search` tool. + public partial class FileSearchToolResource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal FileSearchToolResource() + { + VectorStoreIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// The ID of the vector store attached to this assistant. There can be a maximum of 1 vector + /// store attached to the assistant. + /// + /// Keeps track of any properties unknown to the library. + internal FileSearchToolResource(IReadOnlyList vectorStoreIds, IDictionary serializedAdditionalRawData) + { + VectorStoreIds = vectorStoreIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The ID of the vector store attached to this assistant. There can be a maximum of 1 vector + /// store attached to the assistant. + /// + public IReadOnlyList VectorStoreIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileState.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileState.cs new file mode 100644 index 000000000000..47ce58179d3d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FileState.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The state of the file. + public readonly partial struct FileState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadedValue = "uploaded"; + private const string PendingValue = "pending"; + private const string RunningValue = "running"; + private const string ProcessedValue = "processed"; + private const string ErrorValue = "error"; + private const string DeletingValue = "deleting"; + private const string DeletedValue = "deleted"; + + /// + /// The file has been uploaded but it's not yet processed. This state is not returned by Azure OpenAI and exposed only for + /// compatibility. It can be categorized as an inactive state. + /// + public static FileState Uploaded { get; } = new FileState(UploadedValue); + /// The operation was created and is not queued to be processed in the future. It can be categorized as an inactive state. + public static FileState Pending { get; } = new FileState(PendingValue); + /// The operation has started to be processed. It can be categorized as an active state. + public static FileState Running { get; } = new FileState(RunningValue); + /// The operation has successfully processed and is ready for consumption. It can be categorized as a terminal state. + public static FileState Processed { get; } = new FileState(ProcessedValue); + /// The operation has completed processing with a failure and cannot be further consumed. It can be categorized as a terminal state. + public static FileState Error { get; } = new FileState(ErrorValue); + /// + /// The entity is in the process to be deleted. This state is not returned by Azure OpenAI and exposed only for compatibility. + /// It can be categorized as an active state. + /// + public static FileState Deleting { get; } = new FileState(DeletingValue); + /// + /// The entity has been deleted but may still be referenced by other entities predating the deletion. It can be categorized as a + /// terminal state. + /// + public static FileState Deleted { get; } = new FileState(DeletedValue); + /// Determines if two values are the same. + public static bool operator ==(FileState left, FileState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileState left, FileState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileState(string value) => new FileState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileState other && Equals(other); + /// + public bool Equals(FileState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.Serialization.cs new file mode 100644 index 000000000000..fb4ff9ca04a5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class FunctionName : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionName)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FunctionName IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionName)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionName(document.RootElement, options); + } + + internal static FunctionName DeserializeFunctionName(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionName(name, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FunctionName)} does not support writing '{options.Format}' format."); + } + } + + FunctionName IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionName(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionName)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionName FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionName(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.cs new file mode 100644 index 000000000000..70fcf993d4ae --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/FunctionName.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The function name that will be used, if using the `function` tool. + public partial class FunctionName + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to call. + /// is null. + public FunctionName(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// The name of the function to call. + /// Keeps track of any properties unknown to the library. + internal FunctionName(string name, IDictionary serializedAdditionalRawData) + { + Name = name; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionName() + { + } + + /// The name of the function to call. + public string Name { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/IncompleteRunDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/IncompleteRunDetails.cs new file mode 100644 index 000000000000..373733568f34 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/IncompleteRunDetails.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run. + public readonly partial struct IncompleteRunDetails : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public IncompleteRunDetails(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string MaxCompletionTokensValue = "max_completion_tokens"; + private const string MaxPromptTokensValue = "max_prompt_tokens"; + + /// Maximum completion tokens exceeded. + public static IncompleteRunDetails MaxCompletionTokens { get; } = new IncompleteRunDetails(MaxCompletionTokensValue); + /// Maximum prompt tokens exceeded. + public static IncompleteRunDetails MaxPromptTokens { get; } = new IncompleteRunDetails(MaxPromptTokensValue); + /// Determines if two values are the same. + public static bool operator ==(IncompleteRunDetails left, IncompleteRunDetails right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(IncompleteRunDetails left, IncompleteRunDetails right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator IncompleteRunDetails(string value) => new IncompleteRunDetails(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is IncompleteRunDetails other && Equals(other); + /// + public bool Equals(IncompleteRunDetails other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatusObject.cs deleted file mode 100644 index 5c52700f6c0f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatusObject.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI.Assistants -{ - /// The InternalAssistantFileDeletionStatus_object. - internal readonly partial struct InternalAssistantFileDeletionStatusObject : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public InternalAssistantFileDeletionStatusObject(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string AssistantFileDeletedValue = "assistant.file.deleted"; - - /// assistant.file.deleted. - public static InternalAssistantFileDeletionStatusObject AssistantFileDeleted { get; } = new InternalAssistantFileDeletionStatusObject(AssistantFileDeletedValue); - /// Determines if two values are the same. - public static bool operator ==(InternalAssistantFileDeletionStatusObject left, InternalAssistantFileDeletionStatusObject right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(InternalAssistantFileDeletionStatusObject left, InternalAssistantFileDeletionStatusObject right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator InternalAssistantFileDeletionStatusObject(string value) => new InternalAssistantFileDeletionStatusObject(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAssistantFileDeletionStatusObject other && Equals(other); - /// - public bool Equals(InternalAssistantFileDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs index eb315c465ad1..89cfab2a18a4 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageImageFileDetails.cs @@ -48,7 +48,7 @@ internal partial class InternalMessageImageFileDetails /// Initializes a new instance of . /// The ID for the file associated with this image. /// is null. - internal InternalMessageImageFileDetails(string internalDetails) + public InternalMessageImageFileDetails(string internalDetails) { Argument.AssertNotNull(internalDetails, nameof(internalDetails)); @@ -70,6 +70,6 @@ internal InternalMessageImageFileDetails() } /// The ID for the file associated with this image. - public string InternalDetails { get; } + public string InternalDetails { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs index 9b7a63c4c392..51a2be6fdef4 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.Serialization.cs @@ -81,7 +81,7 @@ internal static InternalMessageTextDetails DeserializeInternalMessageTextDetails return null; } string value = default; - IReadOnlyList annotations = default; + IList annotations = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs index 7f6a60a62245..4489c4dd184e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextDetails.cs @@ -54,7 +54,7 @@ internal partial class InternalMessageTextDetails /// The available derived classes include and . /// /// or is null. - internal InternalMessageTextDetails(string text, IEnumerable annotations) + public InternalMessageTextDetails(string text, IEnumerable annotations) { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(annotations, nameof(annotations)); @@ -71,7 +71,7 @@ internal InternalMessageTextDetails(string text, IEnumerable and . /// /// Keeps track of any properties unknown to the library. - internal InternalMessageTextDetails(string text, IReadOnlyList annotations, IDictionary serializedAdditionalRawData) + internal InternalMessageTextDetails(string text, IList annotations, IDictionary serializedAdditionalRawData) { Text = text; Annotations = annotations; @@ -84,12 +84,12 @@ internal InternalMessageTextDetails() } /// The text data. - public string Text { get; } + public string Text { get; set; } /// /// A list of annotations associated with this text. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. /// The available derived classes include and . /// - public IReadOnlyList Annotations { get; } + public IList Annotations { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs index 3bbdf07622ce..158100231c04 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFileCitationDetails.cs @@ -49,7 +49,7 @@ internal partial class InternalMessageTextFileCitationDetails /// The ID of the file associated with this citation. /// The specific quote cited in the associated file. /// or is null. - internal InternalMessageTextFileCitationDetails(string fileId, string quote) + public InternalMessageTextFileCitationDetails(string fileId, string quote) { Argument.AssertNotNull(fileId, nameof(fileId)); Argument.AssertNotNull(quote, nameof(quote)); @@ -75,8 +75,8 @@ internal InternalMessageTextFileCitationDetails() } /// The ID of the file associated with this citation. - public string FileId { get; } + public string FileId { get; set; } /// The specific quote cited in the associated file. - public string Quote { get; } + public string Quote { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs index 4b86d66be5a2..f56d8a2f2cce 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalMessageTextFilePathDetails.cs @@ -48,7 +48,7 @@ internal partial class InternalMessageTextFilePathDetails /// Initializes a new instance of . /// The ID of the specific file that the citation is from. /// is null. - internal InternalMessageTextFilePathDetails(string fileId) + public InternalMessageTextFilePathDetails(string fileId) { Argument.AssertNotNull(fileId, nameof(fileId)); @@ -70,6 +70,6 @@ internal InternalMessageTextFilePathDetails() } /// The ID of the specific file that the citation is from. - public string FileId { get; } + public string FileId { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.Serialization.cs new file mode 100644 index 000000000000..757e1dcee158 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.Serialization.cs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageAttachment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageAttachment)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (var item in Tools) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } +#if NET6_0_OR_GREATER + writer.WriteRawValue(item); +#else + using (JsonDocument document = JsonDocument.Parse(item, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageAttachment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageAttachment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageAttachment(document.RootElement, options); + } + + internal static MessageAttachment DeserializeMessageAttachment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IList tools = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("tools"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(BinaryData.FromString(item.GetRawText())); + } + } + tools = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageAttachment(fileId, tools, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageAttachment)} does not support writing '{options.Format}' format."); + } + } + + MessageAttachment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageAttachment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageAttachment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageAttachment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageAttachment(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.cs new file mode 100644 index 000000000000..f905e2a52576 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageAttachment.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// This describes to which tools a file has been attached. + public partial class MessageAttachment + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the file to attach to the message. + /// The tools to add to this file. + /// or is null. + public MessageAttachment(string fileId, IEnumerable tools) + { + Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(tools, nameof(tools)); + + FileId = fileId; + Tools = tools.ToList(); + } + + /// Initializes a new instance of . + /// The ID of the file to attach to the message. + /// The tools to add to this file. + /// Keeps track of any properties unknown to the library. + internal MessageAttachment(string fileId, IList tools, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + Tools = tools; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageAttachment() + { + } + + /// The ID of the file to attach to the message. + public string FileId { get; set; } + /// + /// The tools to add to this file. + /// + /// To assign an object to the element of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public IList Tools { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.Serialization.cs new file mode 100644 index 000000000000..9b27c0a4b619 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDelta : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDelta)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + writer.WritePropertyName("content"u8); + writer.WriteStartArray(); + foreach (var item in Content) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDelta)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDelta(document.RootElement, options); + } + + internal static MessageDelta DeserializeMessageDelta(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageRole role = default; + IReadOnlyList content = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("role"u8)) + { + role = new MessageRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("content"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(MessageDeltaContent.DeserializeMessageDeltaContent(item, options)); + } + content = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDelta(role, content, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDelta)} does not support writing '{options.Format}' format."); + } + } + + MessageDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDelta(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDelta)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDelta(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.cs new file mode 100644 index 000000000000..ec114efcb09d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDelta.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the typed 'delta' payload within a streaming message delta chunk. + public partial class MessageDelta + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The entity that produced the message. + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// is null. + internal MessageDelta(MessageRole role, IEnumerable content) + { + Argument.AssertNotNull(content, nameof(content)); + + Role = role; + Content = content.ToList(); + } + + /// Initializes a new instance of . + /// The entity that produced the message. + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal MessageDelta(MessageRole role, IReadOnlyList content, IDictionary serializedAdditionalRawData) + { + Role = role; + Content = content; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageDelta() + { + } + + /// The entity that produced the message. + public MessageRole Role { get; } + /// + /// The content of the message as an array of text and/or images. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public IReadOnlyList Content { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.Serialization.cs new file mode 100644 index 000000000000..fd7cf3e6bb08 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaChunk : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("delta"u8); + writer.WriteObjectValue(Delta, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDeltaChunk IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaChunk(document.RootElement, options); + } + + internal static MessageDeltaChunk DeserializeMessageDeltaChunk(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + MessageDeltaChunkObject @object = default; + MessageDelta delta = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new MessageDeltaChunkObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("delta"u8)) + { + delta = MessageDelta.DeserializeMessageDelta(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaChunk(id, @object, delta, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaChunk IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaChunk(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaChunk)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaChunk FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaChunk(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.cs similarity index 56% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.cs index a33691868926..3a8984a1a101 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunk.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// Information about a file attached to an assistant thread message. - public partial class MessageFile + /// Represents a message delta i.e. any changed fields on a message during streaming. + public partial class MessageDeltaChunk { /// /// Keeps track of any properties unknown to the library. @@ -45,47 +45,43 @@ public partial class MessageFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The identifier, which can be referenced in API endpoints. - /// The Unix timestamp, in seconds, representing when this object was created. - /// The ID of the message that this file is attached to. - /// or is null. - internal MessageFile(string id, DateTimeOffset createdAt, string messageId) + /// Initializes a new instance of . + /// The identifier of the message, which can be referenced in API endpoints. + /// The delta containing the fields that have changed on the Message. + /// or is null. + internal MessageDeltaChunk(string id, MessageDelta delta) { Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(messageId, nameof(messageId)); + Argument.AssertNotNull(delta, nameof(delta)); Id = id; - CreatedAt = createdAt; - MessageId = messageId; + Delta = delta; } - /// Initializes a new instance of . - /// The identifier, which can be referenced in API endpoints. - /// The object type, which is always 'thread.message.file'. - /// The Unix timestamp, in seconds, representing when this object was created. - /// The ID of the message that this file is attached to. + /// Initializes a new instance of . + /// The identifier of the message, which can be referenced in API endpoints. + /// The object type, which is always `thread.message.delta`. + /// The delta containing the fields that have changed on the Message. /// Keeps track of any properties unknown to the library. - internal MessageFile(string id, string @object, DateTimeOffset createdAt, string messageId, IDictionary serializedAdditionalRawData) + internal MessageDeltaChunk(string id, MessageDeltaChunkObject @object, MessageDelta delta, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; - CreatedAt = createdAt; - MessageId = messageId; + Delta = delta; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal MessageFile() + /// Initializes a new instance of for deserialization. + internal MessageDeltaChunk() { } - /// The identifier, which can be referenced in API endpoints. + /// The identifier of the message, which can be referenced in API endpoints. public string Id { get; } + /// The object type, which is always `thread.message.delta`. + public MessageDeltaChunkObject Object { get; } = MessageDeltaChunkObject.ThreadMessageDelta; - /// The Unix timestamp, in seconds, representing when this object was created. - public DateTimeOffset CreatedAt { get; } - /// The ID of the message that this file is attached to. - public string MessageId { get; } + /// The delta containing the fields that have changed on the Message. + public MessageDelta Delta { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunkObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunkObject.cs new file mode 100644 index 000000000000..b8b58471b5b6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaChunkObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The MessageDeltaChunk_object. + public readonly partial struct MessageDeltaChunkObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageDeltaChunkObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadMessageDeltaValue = "thread.message.delta"; + + /// thread.message.delta. + public static MessageDeltaChunkObject ThreadMessageDelta { get; } = new MessageDeltaChunkObject(ThreadMessageDeltaValue); + /// Determines if two values are the same. + public static bool operator ==(MessageDeltaChunkObject left, MessageDeltaChunkObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageDeltaChunkObject left, MessageDeltaChunkObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageDeltaChunkObject(string value) => new MessageDeltaChunkObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageDeltaChunkObject other && Equals(other); + /// + public bool Equals(MessageDeltaChunkObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.Serialization.cs new file mode 100644 index 000000000000..4fb64165c9f6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.Serialization.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownMessageDeltaContent))] + public partial class MessageDeltaContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDeltaContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaContent(document.RootElement, options); + } + + internal static MessageDeltaContent DeserializeMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "image_file": return MessageDeltaImageFileContent.DeserializeMessageDeltaImageFileContent(element, options); + case "text": return MessageDeltaTextContentObject.DeserializeMessageDeltaTextContentObject(element, options); + } + } + return UnknownMessageDeltaContent.DeserializeUnknownMessageDeltaContent(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.cs new file mode 100644 index 000000000000..454d8e437f56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaContent.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a partial streamed message content payload. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class MessageDeltaContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the content part of the message. + protected MessageDeltaContent(int index) + { + Index = index; + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaContent(int index, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaContent() + { + } + + /// The index of the content part of the message. + public int Index { get; } + /// The type of content for this content part. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.Serialization.cs new file mode 100644 index 000000000000..6bb7eb0f9d16 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.Serialization.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaImageFileContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaImageFileContent)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(ImageFile)) + { + writer.WritePropertyName("image_file"u8); + writer.WriteObjectValue(ImageFile, options); + } + } + + MessageDeltaImageFileContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaImageFileContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaImageFileContent(document.RootElement, options); + } + + internal static MessageDeltaImageFileContent DeserializeMessageDeltaImageFileContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaImageFileContentObject imageFile = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("image_file"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + imageFile = MessageDeltaImageFileContentObject.DeserializeMessageDeltaImageFileContentObject(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaImageFileContent(index, type, serializedAdditionalRawData, imageFile); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaImageFileContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaImageFileContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaImageFileContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaImageFileContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaImageFileContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaImageFileContent(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.cs new file mode 100644 index 000000000000..212421c7c2e7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContent.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed image file content part within a streaming message delta chunk. + public partial class MessageDeltaImageFileContent : MessageDeltaContent + { + /// Initializes a new instance of . + /// The index of the content part of the message. + internal MessageDeltaImageFileContent(int index) : base(index) + { + Type = "image_file"; + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + /// The image_file data. + internal MessageDeltaImageFileContent(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaImageFileContentObject imageFile) : base(index, type, serializedAdditionalRawData) + { + ImageFile = imageFile; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaImageFileContent() + { + } + + /// The image_file data. + public MessageDeltaImageFileContentObject ImageFile { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.Serialization.cs new file mode 100644 index 000000000000..f8452d6289ab --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.Serialization.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaImageFileContentObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaImageFileContentObject)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDeltaImageFileContentObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaImageFileContentObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaImageFileContentObject(document.RootElement, options); + } + + internal static MessageDeltaImageFileContentObject DeserializeMessageDeltaImageFileContentObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaImageFileContentObject(fileId, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaImageFileContentObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaImageFileContentObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaImageFileContentObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaImageFileContentObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaImageFileContentObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaImageFileContentObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.cs new file mode 100644 index 000000000000..592b0e9cef60 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaImageFileContentObject.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the 'image_file' payload within streaming image file content. + public partial class MessageDeltaImageFileContentObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaImageFileContentObject() + { + } + + /// Initializes a new instance of . + /// The file ID of the image in the message content. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaImageFileContentObject(string fileId, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The file ID of the image in the message content. + public string FileId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.Serialization.cs new file mode 100644 index 000000000000..e17d766b64e0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.Serialization.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownMessageDeltaTextAnnotation))] + public partial class MessageDeltaTextAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDeltaTextAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + + internal static MessageDeltaTextAnnotation DeserializeMessageDeltaTextAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "file_citation": return MessageDeltaTextFileCitationAnnotationObject.DeserializeMessageDeltaTextFileCitationAnnotationObject(element, options); + case "file_path": return MessageDeltaTextFilePathAnnotationObject.DeserializeMessageDeltaTextFilePathAnnotationObject(element, options); + } + } + return UnknownMessageDeltaTextAnnotation.DeserializeUnknownMessageDeltaTextAnnotation(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextAnnotation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.cs new file mode 100644 index 000000000000..2171bf6148cb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextAnnotation.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a streamed text content part's text annotation. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class MessageDeltaTextAnnotation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + protected MessageDeltaTextAnnotation(int index) + { + Index = index; + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextAnnotation(int index, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextAnnotation() + { + } + + /// The index of the annotation within a text content part. + public int Index { get; } + /// The type of the text content annotation. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.Serialization.cs new file mode 100644 index 000000000000..8f7f833260b9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.Serialization.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextContent)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Value)) + { + writer.WritePropertyName("value"u8); + writer.WriteStringValue(Value); + } + if (Optional.IsCollectionDefined(Annotations)) + { + writer.WritePropertyName("annotations"u8); + writer.WriteStartArray(); + foreach (var item in Annotations) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDeltaTextContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextContent(document.RootElement, options); + } + + internal static MessageDeltaTextContent DeserializeMessageDeltaTextContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string value = default; + IReadOnlyList annotations = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("value"u8)) + { + value = property.Value.GetString(); + continue; + } + if (property.NameEquals("annotations"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(MessageDeltaTextAnnotation.DeserializeMessageDeltaTextAnnotation(item, options)); + } + annotations = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextContent(value, annotations ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.cs new file mode 100644 index 000000000000..15c4cac2d7ca --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContent.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data of a streamed text content part within a streaming message delta chunk. + public partial class MessageDeltaTextContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaTextContent() + { + Annotations = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The data that makes up the text. + /// + /// Annotations for the text. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextContent(string value, IReadOnlyList annotations, IDictionary serializedAdditionalRawData) + { + Value = value; + Annotations = annotations; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The data that makes up the text. + public string Value { get; } + /// + /// Annotations for the text. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public IReadOnlyList Annotations { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.Serialization.cs new file mode 100644 index 000000000000..870b54bc371d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.Serialization.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextContentObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextContentObject)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Text)) + { + writer.WritePropertyName("text"u8); + writer.WriteObjectValue(Text, options); + } + } + + MessageDeltaTextContentObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextContentObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextContentObject(document.RootElement, options); + } + + internal static MessageDeltaTextContentObject DeserializeMessageDeltaTextContentObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaTextContent text = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + text = MessageDeltaTextContent.DeserializeMessageDeltaTextContent(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextContentObject(index, type, serializedAdditionalRawData, text); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextContentObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextContentObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextContentObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextContentObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaTextContentObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextContentObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.cs new file mode 100644 index 000000000000..54247431988a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextContentObject.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed text content part within a streaming message delta chunk. + public partial class MessageDeltaTextContentObject : MessageDeltaContent + { + /// Initializes a new instance of . + /// The index of the content part of the message. + internal MessageDeltaTextContentObject(int index) : base(index) + { + Type = "text"; + } + + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + /// The text content details. + internal MessageDeltaTextContentObject(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaTextContent text) : base(index, type, serializedAdditionalRawData) + { + Text = text; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextContentObject() + { + } + + /// The text content details. + public MessageDeltaTextContent Text { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.Serialization.cs new file mode 100644 index 000000000000..ee069d01c29e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.Serialization.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFileCitationAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotation)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (Optional.IsDefined(Quote)) + { + writer.WritePropertyName("quote"u8); + writer.WriteStringValue(Quote); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDeltaTextFileCitationAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFileCitationAnnotation(document.RootElement, options); + } + + internal static MessageDeltaTextFileCitationAnnotation DeserializeMessageDeltaTextFileCitationAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + string quote = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("quote"u8)) + { + quote = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFileCitationAnnotation(fileId, quote, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFileCitationAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFileCitationAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextFileCitationAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFileCitationAnnotation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.cs new file mode 100644 index 000000000000..6f2fd703c231 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotation.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data of a streamed file citation as applied to a streaming text content part. + public partial class MessageDeltaTextFileCitationAnnotation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaTextFileCitationAnnotation() + { + } + + /// Initializes a new instance of . + /// The ID of the specific file the citation is from. + /// The specific quote in the cited file. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextFileCitationAnnotation(string fileId, string quote, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + Quote = quote; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The ID of the specific file the citation is from. + public string FileId { get; } + /// The specific quote in the cited file. + public string Quote { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.Serialization.cs new file mode 100644 index 000000000000..1d631f9bded1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.Serialization.cs @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFileCitationAnnotationObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotationObject)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(FileCitation)) + { + writer.WritePropertyName("file_citation"u8); + writer.WriteObjectValue(FileCitation, options); + } + if (Optional.IsDefined(Text)) + { + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + } + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } + } + + MessageDeltaTextFileCitationAnnotationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotationObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFileCitationAnnotationObject(document.RootElement, options); + } + + internal static MessageDeltaTextFileCitationAnnotationObject DeserializeMessageDeltaTextFileCitationAnnotationObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaTextFileCitationAnnotation fileCitation = default; + string text = default; + int? startIndex = default; + int? endIndex = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_citation"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileCitation = MessageDeltaTextFileCitationAnnotation.DeserializeMessageDeltaTextFileCitationAnnotation(property.Value, options); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("start_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("end_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFileCitationAnnotationObject( + index, + type, + serializedAdditionalRawData, + fileCitation, + text, + startIndex, + endIndex); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotationObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFileCitationAnnotationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFileCitationAnnotationObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFileCitationAnnotationObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaTextFileCitationAnnotationObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFileCitationAnnotationObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.cs new file mode 100644 index 000000000000..1a67dafe8dfa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFileCitationAnnotationObject.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed file citation applied to a streaming text content part. + public partial class MessageDeltaTextFileCitationAnnotationObject : MessageDeltaTextAnnotation + { + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + internal MessageDeltaTextFileCitationAnnotationObject(int index) : base(index) + { + Type = "file_citation"; + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + /// The file citation information. + /// The text in the message content that needs to be replaced. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + internal MessageDeltaTextFileCitationAnnotationObject(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaTextFileCitationAnnotation fileCitation, string text, int? startIndex, int? endIndex) : base(index, type, serializedAdditionalRawData) + { + FileCitation = fileCitation; + Text = text; + StartIndex = startIndex; + EndIndex = endIndex; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextFileCitationAnnotationObject() + { + } + + /// The file citation information. + public MessageDeltaTextFileCitationAnnotation FileCitation { get; } + /// The text in the message content that needs to be replaced. + public string Text { get; } + /// The start index of this annotation in the content text. + public int? StartIndex { get; } + /// The end index of this annotation in the content text. + public int? EndIndex { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.Serialization.cs new file mode 100644 index 000000000000..57e4b12964f9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.Serialization.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFilePathAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotation)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageDeltaTextFilePathAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFilePathAnnotation(document.RootElement, options); + } + + internal static MessageDeltaTextFilePathAnnotation DeserializeMessageDeltaTextFilePathAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFilePathAnnotation(fileId, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFilePathAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFilePathAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageDeltaTextFilePathAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFilePathAnnotation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.cs new file mode 100644 index 000000000000..dbdd8626dc56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotation.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data of a streamed file path annotation as applied to a streaming text content part. + public partial class MessageDeltaTextFilePathAnnotation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal MessageDeltaTextFilePathAnnotation() + { + } + + /// Initializes a new instance of . + /// The file ID for the annotation. + /// Keeps track of any properties unknown to the library. + internal MessageDeltaTextFilePathAnnotation(string fileId, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The file ID for the annotation. + public string FileId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.Serialization.cs new file mode 100644 index 000000000000..8c54af2bbcc6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.Serialization.cs @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageDeltaTextFilePathAnnotationObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotationObject)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(FilePath)) + { + writer.WritePropertyName("file_path"u8); + writer.WriteObjectValue(FilePath, options); + } + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } + if (Optional.IsDefined(Text)) + { + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + } + } + + MessageDeltaTextFilePathAnnotationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotationObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextFilePathAnnotationObject(document.RootElement, options); + } + + internal static MessageDeltaTextFilePathAnnotationObject DeserializeMessageDeltaTextFilePathAnnotationObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageDeltaTextFilePathAnnotation filePath = default; + int? startIndex = default; + int? endIndex = default; + string text = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_path"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + filePath = MessageDeltaTextFilePathAnnotation.DeserializeMessageDeltaTextFilePathAnnotation(property.Value, options); + continue; + } + if (property.NameEquals("start_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("end_index"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageDeltaTextFilePathAnnotationObject( + index, + type, + serializedAdditionalRawData, + filePath, + startIndex, + endIndex, + text); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotationObject)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextFilePathAnnotationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFilePathAnnotationObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextFilePathAnnotationObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MessageDeltaTextFilePathAnnotationObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextFilePathAnnotationObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.cs new file mode 100644 index 000000000000..85df4f20c57d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageDeltaTextFilePathAnnotationObject.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a streamed file path annotation applied to a streaming text content part. + public partial class MessageDeltaTextFilePathAnnotationObject : MessageDeltaTextAnnotation + { + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + internal MessageDeltaTextFilePathAnnotationObject(int index) : base(index) + { + Type = "file_path"; + } + + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + /// The file path information. + /// The start index of this annotation in the content text. + /// The end index of this annotation in the content text. + /// The text in the message content that needs to be replaced. + internal MessageDeltaTextFilePathAnnotationObject(int index, string type, IDictionary serializedAdditionalRawData, MessageDeltaTextFilePathAnnotation filePath, int? startIndex, int? endIndex, string text) : base(index, type, serializedAdditionalRawData) + { + FilePath = filePath; + StartIndex = startIndex; + EndIndex = endIndex; + Text = text; + } + + /// Initializes a new instance of for deserialization. + internal MessageDeltaTextFilePathAnnotationObject() + { + } + + /// The file path information. + public MessageDeltaTextFilePathAnnotation FilePath { get; } + /// The start index of this annotation in the content text. + public int? StartIndex { get; } + /// The end index of this annotation in the content text. + public int? EndIndex { get; } + /// The text in the message content that needs to be replaced. + public string Text { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs index 8997ff05b177..7e252658ea5e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageImageFileContent.cs @@ -16,7 +16,7 @@ public partial class MessageImageFileContent : MessageContent /// Initializes a new instance of . /// The image file for this thread message content item. /// is null. - internal MessageImageFileContent(InternalMessageImageFileDetails internalDetails) + public MessageImageFileContent(InternalMessageImageFileDetails internalDetails) { Argument.AssertNotNull(internalDetails, nameof(internalDetails)); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.Serialization.cs new file mode 100644 index 000000000000..6faa89be320e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class MessageIncompleteDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageIncompleteDetails)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("reason"u8); + writer.WriteStringValue(Reason.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MessageIncompleteDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageIncompleteDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageIncompleteDetails(document.RootElement, options); + } + + internal static MessageIncompleteDetails DeserializeMessageIncompleteDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MessageIncompleteDetailsReason reason = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("reason"u8)) + { + reason = new MessageIncompleteDetailsReason(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MessageIncompleteDetails(reason, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageIncompleteDetails)} does not support writing '{options.Format}' format."); + } + } + + MessageIncompleteDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageIncompleteDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageIncompleteDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MessageIncompleteDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageIncompleteDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.cs new file mode 100644 index 000000000000..335c1009db7f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetails.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Information providing additional detail about a message entering an incomplete status. + public partial class MessageIncompleteDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The provided reason describing why the message was marked as incomplete. + public MessageIncompleteDetails(MessageIncompleteDetailsReason reason) + { + Reason = reason; + } + + /// Initializes a new instance of . + /// The provided reason describing why the message was marked as incomplete. + /// Keeps track of any properties unknown to the library. + internal MessageIncompleteDetails(MessageIncompleteDetailsReason reason, IDictionary serializedAdditionalRawData) + { + Reason = reason; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MessageIncompleteDetails() + { + } + + /// The provided reason describing why the message was marked as incomplete. + public MessageIncompleteDetailsReason Reason { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetailsReason.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetailsReason.cs new file mode 100644 index 000000000000..ec0c57835d91 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageIncompleteDetailsReason.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A set of reasons describing why a message is marked as incomplete. + public readonly partial struct MessageIncompleteDetailsReason : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageIncompleteDetailsReason(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ContentFilterValue = "content_filter"; + private const string MaxTokensValue = "max_tokens"; + private const string RunCancelledValue = "run_cancelled"; + private const string RunFailedValue = "run_failed"; + private const string RunExpiredValue = "run_expired"; + + /// The run generating the message was terminated due to content filter flagging. + public static MessageIncompleteDetailsReason ContentFilter { get; } = new MessageIncompleteDetailsReason(ContentFilterValue); + /// The run generating the message exhausted available tokens before completion. + public static MessageIncompleteDetailsReason MaxTokens { get; } = new MessageIncompleteDetailsReason(MaxTokensValue); + /// The run generating the message was cancelled before completion. + public static MessageIncompleteDetailsReason RunCancelled { get; } = new MessageIncompleteDetailsReason(RunCancelledValue); + /// The run generating the message failed. + public static MessageIncompleteDetailsReason RunFailed { get; } = new MessageIncompleteDetailsReason(RunFailedValue); + /// The run generating the message expired. + public static MessageIncompleteDetailsReason RunExpired { get; } = new MessageIncompleteDetailsReason(RunExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(MessageIncompleteDetailsReason left, MessageIncompleteDetailsReason right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageIncompleteDetailsReason left, MessageIncompleteDetailsReason right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageIncompleteDetailsReason(string value) => new MessageIncompleteDetailsReason(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageIncompleteDetailsReason other && Equals(other); + /// + public bool Equals(MessageIncompleteDetailsReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStatus.cs new file mode 100644 index 000000000000..d63a6bcf8b56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStatus.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The possible execution status values for a thread message. + public readonly partial struct MessageStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string IncompleteValue = "incomplete"; + private const string CompletedValue = "completed"; + + /// A run is currently creating this message. + public static MessageStatus InProgress { get; } = new MessageStatus(InProgressValue); + /// This message is incomplete. See incomplete_details for more information. + public static MessageStatus Incomplete { get; } = new MessageStatus(IncompleteValue); + /// This message was successfully completed by a run. + public static MessageStatus Completed { get; } = new MessageStatus(CompletedValue); + /// Determines if two values are the same. + public static bool operator ==(MessageStatus left, MessageStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageStatus left, MessageStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageStatus(string value) => new MessageStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageStatus other && Equals(other); + /// + public bool Equals(MessageStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStreamEvent.cs new file mode 100644 index 000000000000..13c90b7d0b77 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageStreamEvent.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Message operation related streaming events. + public readonly partial struct MessageStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public MessageStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadMessageCreatedValue = "thread.message.created"; + private const string ThreadMessageInProgressValue = "thread.message.in_progress"; + private const string ThreadMessageDeltaValue = "thread.message.delta"; + private const string ThreadMessageCompletedValue = "thread.message.completed"; + private const string ThreadMessageIncompleteValue = "thread.message.incomplete"; + + /// Event sent when a new message is created. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageCreated { get; } = new MessageStreamEvent(ThreadMessageCreatedValue); + /// Event sent when a message moves to `in_progress` status. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageInProgress { get; } = new MessageStreamEvent(ThreadMessageInProgressValue); + /// Event sent when a message is being streamed. The data of this event is of type MessageDeltaChunk. + public static MessageStreamEvent ThreadMessageDelta { get; } = new MessageStreamEvent(ThreadMessageDeltaValue); + /// Event sent when a message is completed. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageCompleted { get; } = new MessageStreamEvent(ThreadMessageCompletedValue); + /// Event sent before a message is completed. The data of this event is of type ThreadMessage. + public static MessageStreamEvent ThreadMessageIncomplete { get; } = new MessageStreamEvent(ThreadMessageIncompleteValue); + /// Determines if two values are the same. + public static bool operator ==(MessageStreamEvent left, MessageStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(MessageStreamEvent left, MessageStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator MessageStreamEvent(string value) => new MessageStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is MessageStreamEvent other && Equals(other); + /// + public bool Equals(MessageStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs index fdc1994429ae..0a4c9644f85e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.Serialization.cs @@ -38,10 +38,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteStringValue(Type); writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); - writer.WritePropertyName("start_index"u8); - writer.WriteNumberValue(StartIndex); - writer.WritePropertyName("end_index"u8); - writer.WriteNumberValue(EndIndex); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs index 082f8fea6a5b..aa8769d7ed21 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextAnnotation.cs @@ -51,30 +51,22 @@ public abstract partial class MessageTextAnnotation /// Initializes a new instance of . /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// is null. - protected MessageTextAnnotation(string text, int startIndex, int endIndex) + protected MessageTextAnnotation(string text) { Argument.AssertNotNull(text, nameof(text)); Text = text; - StartIndex = startIndex; - EndIndex = endIndex; } /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. - internal MessageTextAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData) + internal MessageTextAnnotation(string type, string text, IDictionary serializedAdditionalRawData) { Type = type; Text = text; - StartIndex = startIndex; - EndIndex = endIndex; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -86,10 +78,6 @@ internal MessageTextAnnotation() /// The object type. internal string Type { get; set; } /// The textual content associated with this text annotation item. - public string Text { get; } - /// The first text index associated with this text annotation. - public int StartIndex { get; } - /// The last text index associated with this text annotation. - public int EndIndex { get; } + public string Text { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs index 61d7241bb927..ef579043014c 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextContent.cs @@ -16,7 +16,7 @@ public partial class MessageTextContent : MessageContent /// Initializes a new instance of . /// The text and associated annotations for this thread message content item. /// is null. - internal MessageTextContent(InternalMessageTextDetails internalDetails) + public MessageTextContent(InternalMessageTextDetails internalDetails) { Argument.AssertNotNull(internalDetails, nameof(internalDetails)); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs index 678600787d28..3a0adb7f527f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.Serialization.cs @@ -37,6 +37,16 @@ protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWri base.JsonModelWriteCore(writer, options); writer.WritePropertyName("file_citation"u8); writer.WriteObjectValue(InternalDetails, options); + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } } MessageTextFileCitationAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) @@ -60,10 +70,10 @@ internal static MessageTextFileCitationAnnotation DeserializeMessageTextFileCita return null; } InternalMessageTextFileCitationDetails fileCitation = default; + int? startIndex = default; + int? endIndex = default; string type = default; string text = default; - int startIndex = default; - int endIndex = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -73,24 +83,32 @@ internal static MessageTextFileCitationAnnotation DeserializeMessageTextFileCita fileCitation = InternalMessageTextFileCitationDetails.DeserializeInternalMessageTextFileCitationDetails(property.Value, options); continue; } - if (property.NameEquals("type"u8)) + if (property.NameEquals("start_index"u8)) { - type = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("text"u8)) + if (property.NameEquals("end_index"u8)) { - text = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("start_index"u8)) + if (property.NameEquals("type"u8)) { - startIndex = property.Value.GetInt32(); + type = property.Value.GetString(); continue; } - if (property.NameEquals("end_index"u8)) + if (property.NameEquals("text"u8)) { - endIndex = property.Value.GetInt32(); + text = property.Value.GetString(); continue; } if (options.Format != "W") @@ -102,10 +120,10 @@ internal static MessageTextFileCitationAnnotation DeserializeMessageTextFileCita return new MessageTextFileCitationAnnotation( type, text, - startIndex, - endIndex, serializedAdditionalRawData, - fileCitation); + fileCitation, + startIndex, + endIndex); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs index a036ec9b468b..6db943f9c9a3 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFileCitationAnnotation.cs @@ -10,19 +10,17 @@ namespace Azure.AI.OpenAI.Assistants { - /// A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the 'retrieval' tool to search files. + /// A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the 'file_search' tool to search files. public partial class MessageTextFileCitationAnnotation : MessageTextAnnotation { /// Initializes a new instance of . /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// /// A citation within the message that points to a specific quote from a specific file. - /// Generated when the assistant uses the "retrieval" tool to search files. + /// Generated when the assistant uses the "file_search" tool to search files. /// /// or is null. - internal MessageTextFileCitationAnnotation(string text, int startIndex, int endIndex, InternalMessageTextFileCitationDetails internalDetails) : base(text, startIndex, endIndex) + public MessageTextFileCitationAnnotation(string text, InternalMessageTextFileCitationDetails internalDetails) : base(text) { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(internalDetails, nameof(internalDetails)); @@ -34,21 +32,27 @@ internal MessageTextFileCitationAnnotation(string text, int startIndex, int endI /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. /// /// A citation within the message that points to a specific quote from a specific file. - /// Generated when the assistant uses the "retrieval" tool to search files. + /// Generated when the assistant uses the "file_search" tool to search files. /// - internal MessageTextFileCitationAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData, InternalMessageTextFileCitationDetails internalDetails) : base(type, text, startIndex, endIndex, serializedAdditionalRawData) + /// The first text index associated with this text annotation. + /// The last text index associated with this text annotation. + internal MessageTextFileCitationAnnotation(string type, string text, IDictionary serializedAdditionalRawData, InternalMessageTextFileCitationDetails internalDetails, int? startIndex, int? endIndex) : base(type, text, serializedAdditionalRawData) { InternalDetails = internalDetails; + StartIndex = startIndex; + EndIndex = endIndex; } /// Initializes a new instance of for deserialization. internal MessageTextFileCitationAnnotation() { } + /// The first text index associated with this text annotation. + public int? StartIndex { get; set; } + /// The last text index associated with this text annotation. + public int? EndIndex { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs index 2ce71641798e..ed63ad704b75 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.Serialization.cs @@ -37,6 +37,16 @@ protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWri base.JsonModelWriteCore(writer, options); writer.WritePropertyName("file_path"u8); writer.WriteObjectValue(InternalDetails, options); + if (Optional.IsDefined(StartIndex)) + { + writer.WritePropertyName("start_index"u8); + writer.WriteNumberValue(StartIndex.Value); + } + if (Optional.IsDefined(EndIndex)) + { + writer.WritePropertyName("end_index"u8); + writer.WriteNumberValue(EndIndex.Value); + } } MessageTextFilePathAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) @@ -60,10 +70,10 @@ internal static MessageTextFilePathAnnotation DeserializeMessageTextFilePathAnno return null; } InternalMessageTextFilePathDetails filePath = default; + int? startIndex = default; + int? endIndex = default; string type = default; string text = default; - int startIndex = default; - int endIndex = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -73,24 +83,32 @@ internal static MessageTextFilePathAnnotation DeserializeMessageTextFilePathAnno filePath = InternalMessageTextFilePathDetails.DeserializeInternalMessageTextFilePathDetails(property.Value, options); continue; } - if (property.NameEquals("type"u8)) + if (property.NameEquals("start_index"u8)) { - type = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + startIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("text"u8)) + if (property.NameEquals("end_index"u8)) { - text = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + endIndex = property.Value.GetInt32(); continue; } - if (property.NameEquals("start_index"u8)) + if (property.NameEquals("type"u8)) { - startIndex = property.Value.GetInt32(); + type = property.Value.GetString(); continue; } - if (property.NameEquals("end_index"u8)) + if (property.NameEquals("text"u8)) { - endIndex = property.Value.GetInt32(); + text = property.Value.GetString(); continue; } if (options.Format != "W") @@ -102,10 +120,10 @@ internal static MessageTextFilePathAnnotation DeserializeMessageTextFilePathAnno return new MessageTextFilePathAnnotation( type, text, - startIndex, - endIndex, serializedAdditionalRawData, - filePath); + filePath, + startIndex, + endIndex); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs index 787c70831f54..276bb7ded43d 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/MessageTextFilePathAnnotation.cs @@ -15,11 +15,9 @@ public partial class MessageTextFilePathAnnotation : MessageTextAnnotation { /// Initializes a new instance of . /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// A URL for the file that's generated when the assistant used the code_interpreter tool to generate a file. /// or is null. - internal MessageTextFilePathAnnotation(string text, int startIndex, int endIndex, InternalMessageTextFilePathDetails internalDetails) : base(text, startIndex, endIndex) + public MessageTextFilePathAnnotation(string text, InternalMessageTextFilePathDetails internalDetails) : base(text) { Argument.AssertNotNull(text, nameof(text)); Argument.AssertNotNull(internalDetails, nameof(internalDetails)); @@ -31,18 +29,24 @@ internal MessageTextFilePathAnnotation(string text, int startIndex, int endIndex /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. /// A URL for the file that's generated when the assistant used the code_interpreter tool to generate a file. - internal MessageTextFilePathAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData, InternalMessageTextFilePathDetails internalDetails) : base(type, text, startIndex, endIndex, serializedAdditionalRawData) + /// The first text index associated with this text annotation. + /// The last text index associated with this text annotation. + internal MessageTextFilePathAnnotation(string type, string text, IDictionary serializedAdditionalRawData, InternalMessageTextFilePathDetails internalDetails, int? startIndex, int? endIndex) : base(type, text, serializedAdditionalRawData) { InternalDetails = internalDetails; + StartIndex = startIndex; + EndIndex = endIndex; } /// Initializes a new instance of for deserialization. internal MessageTextFilePathAnnotation() { } + /// The first text index associated with this text annotation. + public int? StartIndex { get; set; } + /// The last text index associated with this text annotation. + public int? EndIndex { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs index 7bb6222023a9..4a2eb30a8a00 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.Serialization.cs @@ -46,6 +46,16 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteNumberValue(CreatedAt, "U"); writer.WritePropertyName("purpose"u8); writer.WriteStringValue(Purpose.ToString()); + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(StatusDetails)) + { + writer.WritePropertyName("status_details"u8); + writer.WriteStringValue(StatusDetails); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -89,6 +99,8 @@ internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReade string filename = default; DateTimeOffset createdAt = default; OpenAIFilePurpose purpose = default; + FileState? status = default; + string statusDetails = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -123,6 +135,20 @@ internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReade purpose = new OpenAIFilePurpose(property.Value.GetString()); continue; } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new FileState(property.Value.GetString()); + continue; + } + if (property.NameEquals("status_details"u8)) + { + statusDetails = property.Value.GetString(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); @@ -136,6 +162,8 @@ internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReade filename, createdAt, purpose, + status, + statusDetails, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs index 318f90d4c5a5..29264237fe5a 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFile.cs @@ -71,8 +71,10 @@ internal OpenAIFile(string id, int size, string filename, DateTimeOffset created /// The name of the file. /// The Unix timestamp, in seconds, representing when this object was created. /// The intended purpose of a file. + /// The state of the file. This field is available in Azure OpenAI only. + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. /// Keeps track of any properties unknown to the library. - internal OpenAIFile(string @object, string id, int size, string filename, DateTimeOffset createdAt, OpenAIFilePurpose purpose, IDictionary serializedAdditionalRawData) + internal OpenAIFile(string @object, string id, int size, string filename, DateTimeOffset createdAt, OpenAIFilePurpose purpose, FileState? status, string statusDetails, IDictionary serializedAdditionalRawData) { Object = @object; Id = id; @@ -80,6 +82,8 @@ internal OpenAIFile(string @object, string id, int size, string filename, DateTi Filename = filename; CreatedAt = createdAt; Purpose = purpose; + Status = status; + StatusDetails = statusDetails; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -98,5 +102,9 @@ internal OpenAIFile() public DateTimeOffset CreatedAt { get; } /// The intended purpose of a file. public OpenAIFilePurpose Purpose { get; } + /// The state of the file. This field is available in Azure OpenAI only. + public FileState? Status { get; } + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. + public string StatusDetails { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs index 50d531cac562..e58119d1b591 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIFilePurpose.cs @@ -26,6 +26,9 @@ public OpenAIFilePurpose(string value) private const string FineTuneResultsValue = "fine-tune-results"; private const string AssistantsValue = "assistants"; private const string AssistantsOutputValue = "assistants_output"; + private const string BatchValue = "batch"; + private const string BatchOutputValue = "batch_output"; + private const string VisionValue = "vision"; /// Indicates a file is used for fine tuning input. public static OpenAIFilePurpose FineTune { get; } = new OpenAIFilePurpose(FineTuneValue); @@ -35,6 +38,12 @@ public OpenAIFilePurpose(string value) public static OpenAIFilePurpose Assistants { get; } = new OpenAIFilePurpose(AssistantsValue); /// Indicates a file is used as output by assistants. public static OpenAIFilePurpose AssistantsOutput { get; } = new OpenAIFilePurpose(AssistantsOutputValue); + /// Indicates a file is used as input to . + public static OpenAIFilePurpose Batch { get; } = new OpenAIFilePurpose(BatchValue); + /// Indicates a file is used as output by a vector store batch operation. + public static OpenAIFilePurpose BatchOutput { get; } = new OpenAIFilePurpose(BatchOutputValue); + /// Indicates a file is used as input to a vision operation. + public static OpenAIFilePurpose Vision { get; } = new OpenAIFilePurpose(VisionValue); /// Determines if two values are the same. public static bool operator ==(OpenAIFilePurpose left, OpenAIFilePurpose right) => left.Equals(right); /// Determines if two values are not the same. diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfAssistantFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfAssistantFileObject.cs deleted file mode 100644 index 1a72c0020e88..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfAssistantFileObject.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI.Assistants -{ - /// The OpenAIPageableListOfAssistantFile_object. - internal readonly partial struct OpenAIPageableListOfAssistantFileObject : IEquatable - { - private readonly string _value; - - /// Initializes a new instance of . - /// is null. - public OpenAIPageableListOfAssistantFileObject(string value) - { - _value = value ?? throw new ArgumentNullException(nameof(value)); - } - - private const string ListValue = "list"; - - /// list. - public static OpenAIPageableListOfAssistantFileObject List { get; } = new OpenAIPageableListOfAssistantFileObject(ListValue); - /// Determines if two values are the same. - public static bool operator ==(OpenAIPageableListOfAssistantFileObject left, OpenAIPageableListOfAssistantFileObject right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(OpenAIPageableListOfAssistantFileObject left, OpenAIPageableListOfAssistantFileObject right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator OpenAIPageableListOfAssistantFileObject(string value) => new OpenAIPageableListOfAssistantFileObject(value); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is OpenAIPageableListOfAssistantFileObject other && Equals(other); - /// - public bool Equals(OpenAIPageableListOfAssistantFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.Serialization.cs similarity index 66% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.Serialization.cs index 0f7226e4395b..f7cc560e9ff4 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class InternalOpenAIPageableListOfMessageFile : IUtf8JsonSerializable, IJsonModel + public partial class OpenAIPageableListOfVectorStore : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,10 +28,10 @@ void IJsonModel.Write(Utf8JsonWriter wr /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfMessageFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support writing '{format}' format."); } writer.WritePropertyName("object"u8); @@ -66,19 +66,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - InternalOpenAIPageableListOfMessageFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStore IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfMessageFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalOpenAIPageableListOfMessageFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStore(document.RootElement, options); } - internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenAIPageableListOfMessageFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIPageableListOfVectorStore DeserializeOpenAIPageableListOfVectorStore(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -86,8 +86,8 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA { return null; } - OpenAIPageableListOfMessageFileObject @object = default; - IReadOnlyList data = default; + OpenAIPageableListOfVectorStoreObject @object = default; + IReadOnlyList data = default; string firstId = default; string lastId = default; bool hasMore = default; @@ -97,15 +97,15 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA { if (property.NameEquals("object"u8)) { - @object = new OpenAIPageableListOfMessageFileObject(property.Value.GetString()); + @object = new OpenAIPageableListOfVectorStoreObject(property.Value.GetString()); continue; } if (property.NameEquals("data"u8)) { - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(MessageFile.DeserializeMessageFile(item, options)); + array.Add(VectorStore.DeserializeVectorStore(item, options)); } data = array; continue; @@ -131,7 +131,7 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA } } serializedAdditionalRawData = rawDataDictionary; - return new InternalOpenAIPageableListOfMessageFile( + return new OpenAIPageableListOfVectorStore( @object, data, firstId, @@ -140,43 +140,43 @@ internal static InternalOpenAIPageableListOfMessageFile DeserializeInternalOpenA serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfMessageFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support writing '{options.Format}' format."); } } - InternalOpenAIPageableListOfMessageFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStore IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeInternalOpenAIPageableListOfMessageFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStore(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfMessageFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStore)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static InternalOpenAIPageableListOfMessageFile FromResponse(Response response) + internal static OpenAIPageableListOfVectorStore FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeInternalOpenAIPageableListOfMessageFile(document.RootElement); + return DeserializeOpenAIPageableListOfVectorStore(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.cs similarity index 78% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.cs index 7b5f1581bf67..1cfa1fd0b07d 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStore.cs @@ -12,7 +12,7 @@ namespace Azure.AI.OpenAI.Assistants { /// The response data for a requested list of items. - internal partial class InternalOpenAIPageableListOfAssistantFile + public partial class OpenAIPageableListOfVectorStore { /// /// Keeps track of any properties unknown to the library. @@ -46,13 +46,13 @@ internal partial class InternalOpenAIPageableListOfAssistantFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// , or is null. - internal InternalOpenAIPageableListOfAssistantFile(IEnumerable data, string firstId, string lastId, bool hasMore) + internal OpenAIPageableListOfVectorStore(IEnumerable data, string firstId, string lastId, bool hasMore) { Argument.AssertNotNull(data, nameof(data)); Argument.AssertNotNull(firstId, nameof(firstId)); @@ -64,14 +64,14 @@ internal InternalOpenAIPageableListOfAssistantFile(IEnumerable da HasMore = hasMore; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The object type, which is always list. /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// Keeps track of any properties unknown to the library. - internal InternalOpenAIPageableListOfAssistantFile(OpenAIPageableListOfAssistantFileObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal OpenAIPageableListOfVectorStore(OpenAIPageableListOfVectorStoreObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) { Object = @object; Data = data; @@ -81,16 +81,16 @@ internal InternalOpenAIPageableListOfAssistantFile(OpenAIPageableListOfAssistant _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalOpenAIPageableListOfAssistantFile() + /// Initializes a new instance of for deserialization. + internal OpenAIPageableListOfVectorStore() { } /// The object type, which is always list. - public OpenAIPageableListOfAssistantFileObject Object { get; } = OpenAIPageableListOfAssistantFileObject.List; + public OpenAIPageableListOfVectorStoreObject Object { get; } = OpenAIPageableListOfVectorStoreObject.List; /// The requested list of items. - public IReadOnlyList Data { get; } + public IReadOnlyList Data { get; } /// The first ID represented in this list. public string FirstId { get; } /// The last ID represented in this list. diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.Serialization.cs similarity index 65% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.Serialization.cs index 1408fa34d5f6..d3ad52c01a1f 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfAssistantFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class InternalOpenAIPageableListOfAssistantFile : IUtf8JsonSerializable, IJsonModel + public partial class OpenAIPageableListOfVectorStoreFile : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,10 +28,10 @@ void IJsonModel.Write(Utf8JsonWriter /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfAssistantFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support writing '{format}' format."); } writer.WritePropertyName("object"u8); @@ -66,19 +66,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - InternalOpenAIPageableListOfAssistantFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStoreFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfAssistantFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalOpenAIPageableListOfAssistantFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStoreFile(document.RootElement, options); } - internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpenAIPageableListOfAssistantFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static OpenAIPageableListOfVectorStoreFile DeserializeOpenAIPageableListOfVectorStoreFile(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -86,8 +86,8 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe { return null; } - OpenAIPageableListOfAssistantFileObject @object = default; - IReadOnlyList data = default; + OpenAIPageableListOfVectorStoreFileObject @object = default; + IReadOnlyList data = default; string firstId = default; string lastId = default; bool hasMore = default; @@ -97,15 +97,15 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe { if (property.NameEquals("object"u8)) { - @object = new OpenAIPageableListOfAssistantFileObject(property.Value.GetString()); + @object = new OpenAIPageableListOfVectorStoreFileObject(property.Value.GetString()); continue; } if (property.NameEquals("data"u8)) { - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(AssistantFile.DeserializeAssistantFile(item, options)); + array.Add(VectorStoreFile.DeserializeVectorStoreFile(item, options)); } data = array; continue; @@ -131,7 +131,7 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe } } serializedAdditionalRawData = rawDataDictionary; - return new InternalOpenAIPageableListOfAssistantFile( + return new OpenAIPageableListOfVectorStoreFile( @object, data, firstId, @@ -140,43 +140,43 @@ internal static InternalOpenAIPageableListOfAssistantFile DeserializeInternalOpe serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfAssistantFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support writing '{options.Format}' format."); } } - InternalOpenAIPageableListOfAssistantFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + OpenAIPageableListOfVectorStoreFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeInternalOpenAIPageableListOfAssistantFile(document.RootElement, options); + return DeserializeOpenAIPageableListOfVectorStoreFile(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalOpenAIPageableListOfAssistantFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(OpenAIPageableListOfVectorStoreFile)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static InternalOpenAIPageableListOfAssistantFile FromResponse(Response response) + internal static OpenAIPageableListOfVectorStoreFile FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeInternalOpenAIPageableListOfAssistantFile(document.RootElement); + return DeserializeOpenAIPageableListOfVectorStoreFile(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.cs similarity index 78% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.cs index 591f029940a1..8f4e487d59ad 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalOpenAIPageableListOfMessageFile.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFile.cs @@ -12,7 +12,7 @@ namespace Azure.AI.OpenAI.Assistants { /// The response data for a requested list of items. - internal partial class InternalOpenAIPageableListOfMessageFile + public partial class OpenAIPageableListOfVectorStoreFile { /// /// Keeps track of any properties unknown to the library. @@ -46,13 +46,13 @@ internal partial class InternalOpenAIPageableListOfMessageFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// , or is null. - internal InternalOpenAIPageableListOfMessageFile(IEnumerable data, string firstId, string lastId, bool hasMore) + internal OpenAIPageableListOfVectorStoreFile(IEnumerable data, string firstId, string lastId, bool hasMore) { Argument.AssertNotNull(data, nameof(data)); Argument.AssertNotNull(firstId, nameof(firstId)); @@ -64,14 +64,14 @@ internal InternalOpenAIPageableListOfMessageFile(IEnumerable data, HasMore = hasMore; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The object type, which is always list. /// The requested list of items. /// The first ID represented in this list. /// The last ID represented in this list. /// A value indicating whether there are additional values available not captured in this list. /// Keeps track of any properties unknown to the library. - internal InternalOpenAIPageableListOfMessageFile(OpenAIPageableListOfMessageFileObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) + internal OpenAIPageableListOfVectorStoreFile(OpenAIPageableListOfVectorStoreFileObject @object, IReadOnlyList data, string firstId, string lastId, bool hasMore, IDictionary serializedAdditionalRawData) { Object = @object; Data = data; @@ -81,16 +81,16 @@ internal InternalOpenAIPageableListOfMessageFile(OpenAIPageableListOfMessageFile _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalOpenAIPageableListOfMessageFile() + /// Initializes a new instance of for deserialization. + internal OpenAIPageableListOfVectorStoreFile() { } /// The object type, which is always list. - public OpenAIPageableListOfMessageFileObject Object { get; } = OpenAIPageableListOfMessageFileObject.List; + public OpenAIPageableListOfVectorStoreFileObject Object { get; } = OpenAIPageableListOfVectorStoreFileObject.List; /// The requested list of items. - public IReadOnlyList Data { get; } + public IReadOnlyList Data { get; } /// The first ID represented in this list. public string FirstId { get; } /// The last ID represented in this list. diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFileObject.cs new file mode 100644 index 000000000000..1c678fe63a61 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreFileObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The OpenAIPageableListOfVectorStoreFile_object. + public readonly partial struct OpenAIPageableListOfVectorStoreFileObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OpenAIPageableListOfVectorStoreFileObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static OpenAIPageableListOfVectorStoreFileObject List { get; } = new OpenAIPageableListOfVectorStoreFileObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIPageableListOfVectorStoreFileObject left, OpenAIPageableListOfVectorStoreFileObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIPageableListOfVectorStoreFileObject left, OpenAIPageableListOfVectorStoreFileObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIPageableListOfVectorStoreFileObject(string value) => new OpenAIPageableListOfVectorStoreFileObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OpenAIPageableListOfVectorStoreFileObject other && Equals(other); + /// + public bool Equals(OpenAIPageableListOfVectorStoreFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfMessageFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreObject.cs similarity index 55% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfMessageFileObject.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreObject.cs index 9993d3b6fdec..38b2253eef2e 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfMessageFileObject.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/OpenAIPageableListOfVectorStoreObject.cs @@ -10,14 +10,14 @@ namespace Azure.AI.OpenAI.Assistants { - /// The OpenAIPageableListOfMessageFile_object. - internal readonly partial struct OpenAIPageableListOfMessageFileObject : IEquatable + /// The OpenAIPageableListOfVectorStore_object. + public readonly partial struct OpenAIPageableListOfVectorStoreObject : IEquatable { private readonly string _value; - /// Initializes a new instance of . + /// Initializes a new instance of . /// is null. - public OpenAIPageableListOfMessageFileObject(string value) + public OpenAIPageableListOfVectorStoreObject(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } @@ -25,19 +25,19 @@ public OpenAIPageableListOfMessageFileObject(string value) private const string ListValue = "list"; /// list. - public static OpenAIPageableListOfMessageFileObject List { get; } = new OpenAIPageableListOfMessageFileObject(ListValue); - /// Determines if two values are the same. - public static bool operator ==(OpenAIPageableListOfMessageFileObject left, OpenAIPageableListOfMessageFileObject right) => left.Equals(right); - /// Determines if two values are not the same. - public static bool operator !=(OpenAIPageableListOfMessageFileObject left, OpenAIPageableListOfMessageFileObject right) => !left.Equals(right); - /// Converts a to a . - public static implicit operator OpenAIPageableListOfMessageFileObject(string value) => new OpenAIPageableListOfMessageFileObject(value); + public static OpenAIPageableListOfVectorStoreObject List { get; } = new OpenAIPageableListOfVectorStoreObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIPageableListOfVectorStoreObject left, OpenAIPageableListOfVectorStoreObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIPageableListOfVectorStoreObject left, OpenAIPageableListOfVectorStoreObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIPageableListOfVectorStoreObject(string value) => new OpenAIPageableListOfVectorStoreObject(value); /// [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is OpenAIPageableListOfMessageFileObject other && Equals(other); + public override bool Equals(object obj) => obj is OpenAIPageableListOfVectorStoreObject other && Equals(other); /// - public bool Equals(OpenAIPageableListOfMessageFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + public bool Equals(OpenAIPageableListOfVectorStoreObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// [EditorBrowsable(EditorBrowsableState.Never)] diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.cs deleted file mode 100644 index f2f39855b348..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Assistants -{ - /// The input definition information for a retrieval tool as used to configure an assistant. - public partial class RetrievalToolDefinition : ToolDefinition - { - /// Initializes a new instance of . - public RetrievalToolDefinition() - { - Type = "retrieval"; - } - - /// Initializes a new instance of . - /// The object type. - /// Keeps track of any properties unknown to the library. - internal RetrievalToolDefinition(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) - { - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.Serialization.cs new file mode 100644 index 000000000000..282fd568dd43 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunCompletionUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunCompletionUsage)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("completion_tokens"u8); + writer.WriteNumberValue(CompletionTokens); + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunCompletionUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunCompletionUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunCompletionUsage(document.RootElement, options); + } + + internal static RunCompletionUsage DeserializeRunCompletionUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long completionTokens = default; + long promptTokens = default; + long totalTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("completion_tokens"u8)) + { + completionTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunCompletionUsage)} does not support writing '{options.Format}' format."); + } + } + + RunCompletionUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunCompletionUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunCompletionUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunCompletionUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunCompletionUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.cs new file mode 100644 index 000000000000..2dfd3c2ee2c8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunCompletionUsage.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + public partial class RunCompletionUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run. + /// Number of prompt tokens used over the course of the run. + /// Total number of tokens used (prompt + completion). + internal RunCompletionUsage(long completionTokens, long promptTokens, long totalTokens) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run. + /// Number of prompt tokens used over the course of the run. + /// Total number of tokens used (prompt + completion). + /// Keeps track of any properties unknown to the library. + internal RunCompletionUsage(long completionTokens, long promptTokens, long totalTokens, IDictionary serializedAdditionalRawData) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunCompletionUsage() + { + } + + /// Number of completion tokens used over the course of the run. + public long CompletionTokens { get; } + /// Number of prompt tokens used over the course of the run. + public long PromptTokens { get; } + /// Total number of tokens used (prompt + completion). + public long TotalTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunIncludes.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunIncludes.cs new file mode 100644 index 000000000000..5e0e0daee070 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunIncludes.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Values to for the includes parameter in the create run operation. + public readonly partial struct RunIncludes : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RunIncludes(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FileSearchContentValue = "step_details.tool_calls[*].file_search.results[*].content"; + + /// Fetch the file search result content. + public static RunIncludes FileSearchContent { get; } = new RunIncludes(FileSearchContentValue); + /// Determines if two values are the same. + public static bool operator ==(RunIncludes left, RunIncludes right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RunIncludes left, RunIncludes right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RunIncludes(string value) => new RunIncludes(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RunIncludes other && Equals(other); + /// + public bool Equals(RunIncludes other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs index 3efdb79c0c6a..25e17327254c 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.Serialization.cs @@ -97,6 +97,18 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit { writer.WriteNull("failed_at"); } + if (Optional.IsDefined(Usage)) + { + if (Usage != null) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + else + { + writer.WriteNull("usage"); + } + } if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -163,6 +175,7 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite DateTimeOffset? completedAt = default; DateTimeOffset? cancelledAt = default; DateTimeOffset? failedAt = default; + RunStepCompletionUsage usage = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -243,6 +256,16 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite DeserializeNullableDateTimeOffset(property, ref failedAt); continue; } + if (property.NameEquals("usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + usage = null; + continue; + } + usage = RunStepCompletionUsage.DeserializeRunStepCompletionUsage(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -279,6 +302,7 @@ internal static RunStep DeserializeRunStep(JsonElement element, ModelReaderWrite completedAt, cancelledAt, failedAt, + usage, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs index 9d8d21d55457..3b622f261eb6 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStep.cs @@ -108,9 +108,10 @@ internal RunStep(string id, RunStepType type, string assistantId, string threadI /// The Unix timestamp, in seconds, representing when this completed. /// The Unix timestamp, in seconds, representing when this was cancelled. /// The Unix timestamp, in seconds, representing when this failed. + /// Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal RunStep(string id, string @object, RunStepType type, string assistantId, string threadId, string runId, RunStepStatus status, RunStepDetails stepDetails, RunStepError lastError, DateTimeOffset createdAt, DateTimeOffset? expiredAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal RunStep(string id, string @object, RunStepType type, string assistantId, string threadId, string runId, RunStepStatus status, RunStepDetails stepDetails, RunStepError lastError, DateTimeOffset createdAt, DateTimeOffset? expiredAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, RunStepCompletionUsage usage, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; @@ -126,6 +127,7 @@ internal RunStep(string id, string @object, RunStepType type, string assistantId CompletedAt = completedAt; CancelledAt = cancelledAt; FailedAt = failedAt; + Usage = usage; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -166,6 +168,8 @@ internal RunStep() public DateTimeOffset? CancelledAt { get; } /// The Unix timestamp, in seconds, representing when this failed. public DateTimeOffset? FailedAt { get; } + /// Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`. + public RunStepCompletionUsage Usage { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.Serialization.cs new file mode 100644 index 000000000000..1d6631a4b731 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepCompletionUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepCompletionUsage)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("completion_tokens"u8); + writer.WriteNumberValue(CompletionTokens); + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepCompletionUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepCompletionUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepCompletionUsage(document.RootElement, options); + } + + internal static RunStepCompletionUsage DeserializeRunStepCompletionUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + long completionTokens = default; + long promptTokens = default; + long totalTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("completion_tokens"u8)) + { + completionTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt64(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepCompletionUsage(completionTokens, promptTokens, totalTokens, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepCompletionUsage)} does not support writing '{options.Format}' format."); + } + } + + RunStepCompletionUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepCompletionUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepCompletionUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepCompletionUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepCompletionUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.cs new file mode 100644 index 000000000000..738d57f0df80 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepCompletionUsage.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Usage statistics related to the run step. + public partial class RunStepCompletionUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run step. + /// Number of prompt tokens used over the course of the run step. + /// Total number of tokens used (prompt + completion). + internal RunStepCompletionUsage(long completionTokens, long promptTokens, long totalTokens) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// Number of completion tokens used over the course of the run step. + /// Number of prompt tokens used over the course of the run step. + /// Total number of tokens used (prompt + completion). + /// Keeps track of any properties unknown to the library. + internal RunStepCompletionUsage(long completionTokens, long promptTokens, long totalTokens, IDictionary serializedAdditionalRawData) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepCompletionUsage() + { + } + + /// Number of completion tokens used over the course of the run step. + public long CompletionTokens { get; } + /// Number of prompt tokens used over the course of the run step. + public long PromptTokens { get; } + /// Total number of tokens used (prompt + completion). + public long TotalTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.Serialization.cs new file mode 100644 index 000000000000..fbc756acda1b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDelta : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDelta)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(StepDetails)) + { + writer.WritePropertyName("step_details"u8); + writer.WriteObjectValue(StepDetails, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDelta IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDelta)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDelta(document.RootElement, options); + } + + internal static RunStepDelta DeserializeRunStepDelta(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaDetail stepDetails = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("step_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stepDetails = RunStepDeltaDetail.DeserializeRunStepDeltaDetail(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDelta(stepDetails, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDelta)} does not support writing '{options.Format}' format."); + } + } + + RunStepDelta IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDelta(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDelta)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDelta FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDelta(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.cs new file mode 100644 index 000000000000..9b28f292c68b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDelta.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the delta payload in a streaming run step delta chunk. + public partial class RunStepDelta + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDelta() + { + } + + /// Initializes a new instance of . + /// + /// The details of the run step. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal RunStepDelta(RunStepDeltaDetail stepDetails, IDictionary serializedAdditionalRawData) + { + StepDetails = stepDetails; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The details of the run step. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public RunStepDeltaDetail StepDetails { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.Serialization.cs new file mode 100644 index 000000000000..94cbacc1a0a3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaChunk : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaChunk)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("delta"u8); + writer.WriteObjectValue(Delta, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaChunk IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaChunk)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaChunk(document.RootElement, options); + } + + internal static RunStepDeltaChunk DeserializeRunStepDeltaChunk(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + RunStepDeltaChunkObject @object = default; + RunStepDelta delta = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new RunStepDeltaChunkObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("delta"u8)) + { + delta = RunStepDelta.DeserializeRunStepDelta(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaChunk(id, @object, delta, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaChunk)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaChunk IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaChunk(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaChunk)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaChunk FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaChunk(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.cs new file mode 100644 index 000000000000..b577dd0a9f7d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunk.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a run step delta i.e. any changed fields on a run step during streaming. + public partial class RunStepDeltaChunk + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier of the run step, which can be referenced in API endpoints. + /// The delta containing the fields that have changed on the run step. + /// or is null. + internal RunStepDeltaChunk(string id, RunStepDelta delta) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(delta, nameof(delta)); + + Id = id; + Delta = delta; + } + + /// Initializes a new instance of . + /// The identifier of the run step, which can be referenced in API endpoints. + /// The object type, which is always `thread.run.step.delta`. + /// The delta containing the fields that have changed on the run step. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaChunk(string id, RunStepDeltaChunkObject @object, RunStepDelta delta, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + Delta = delta; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaChunk() + { + } + + /// The identifier of the run step, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `thread.run.step.delta`. + public RunStepDeltaChunkObject Object { get; } = RunStepDeltaChunkObject.ThreadRunStepDelta; + + /// The delta containing the fields that have changed on the run step. + public RunStepDelta Delta { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunkObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunkObject.cs new file mode 100644 index 000000000000..4cadb42a2b35 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaChunkObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The RunStepDeltaChunk_object. + public readonly partial struct RunStepDeltaChunkObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RunStepDeltaChunkObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; + + /// thread.run.step.delta. + public static RunStepDeltaChunkObject ThreadRunStepDelta { get; } = new RunStepDeltaChunkObject(ThreadRunStepDeltaValue); + /// Determines if two values are the same. + public static bool operator ==(RunStepDeltaChunkObject left, RunStepDeltaChunkObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RunStepDeltaChunkObject left, RunStepDeltaChunkObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RunStepDeltaChunkObject(string value) => new RunStepDeltaChunkObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RunStepDeltaChunkObject other && Equals(other); + /// + public bool Equals(RunStepDeltaChunkObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.Serialization.cs new file mode 100644 index 000000000000..6c053796b8bb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.Serialization.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterDetailItemObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterDetailItemObject)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Input)) + { + writer.WritePropertyName("input"u8); + writer.WriteStringValue(Input); + } + if (Optional.IsCollectionDefined(Outputs)) + { + writer.WritePropertyName("outputs"u8); + writer.WriteStartArray(); + foreach (var item in Outputs) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaCodeInterpreterDetailItemObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterDetailItemObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterDetailItemObject(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterDetailItemObject DeserializeRunStepDeltaCodeInterpreterDetailItemObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string input = default; + IReadOnlyList outputs = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("input"u8)) + { + input = property.Value.GetString(); + continue; + } + if (property.NameEquals("outputs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(RunStepDeltaCodeInterpreterOutput.DeserializeRunStepDeltaCodeInterpreterOutput(item, options)); + } + outputs = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterDetailItemObject(input, outputs ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterDetailItemObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterDetailItemObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterDetailItemObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterDetailItemObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaCodeInterpreterDetailItemObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterDetailItemObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.cs new file mode 100644 index 000000000000..d3a655d903d0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterDetailItemObject.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the Code Interpreter tool call data in a streaming run step's tool calls. + public partial class RunStepDeltaCodeInterpreterDetailItemObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaCodeInterpreterDetailItemObject() + { + Outputs = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The input into the Code Interpreter tool call. + /// + /// The outputs from the Code Interpreter tool call. Code Interpreter can output one or more + /// items, including text (`logs`) or images (`image`). Each of these are represented by a + /// different object type. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaCodeInterpreterDetailItemObject(string input, IReadOnlyList outputs, IDictionary serializedAdditionalRawData) + { + Input = input; + Outputs = outputs; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The input into the Code Interpreter tool call. + public string Input { get; } + /// + /// The outputs from the Code Interpreter tool call. Code Interpreter can output one or more + /// items, including text (`logs`) or images (`image`). Each of these are represented by a + /// different object type. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public IReadOnlyList Outputs { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.Serialization.cs new file mode 100644 index 000000000000..593618121d8d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.Serialization.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterImageOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutput)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Image)) + { + writer.WritePropertyName("image"u8); + writer.WriteObjectValue(Image, options); + } + } + + RunStepDeltaCodeInterpreterImageOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterImageOutput(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterImageOutput DeserializeRunStepDeltaCodeInterpreterImageOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaCodeInterpreterImageOutputObject image = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("image"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + image = RunStepDeltaCodeInterpreterImageOutputObject.DeserializeRunStepDeltaCodeInterpreterImageOutputObject(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterImageOutput(index, type, serializedAdditionalRawData, image); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterImageOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterImageOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaCodeInterpreterImageOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterImageOutput(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.cs new file mode 100644 index 000000000000..0d80fac4887c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutput.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents an image output as produced the Code interpreter tool and as represented in a streaming run step's delta tool calls collection. + public partial class RunStepDeltaCodeInterpreterImageOutput : RunStepDeltaCodeInterpreterOutput + { + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + internal RunStepDeltaCodeInterpreterImageOutput(int index) : base(index) + { + Type = "image"; + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + /// The image data for the Code Interpreter tool call output. + internal RunStepDeltaCodeInterpreterImageOutput(int index, string type, IDictionary serializedAdditionalRawData, RunStepDeltaCodeInterpreterImageOutputObject image) : base(index, type, serializedAdditionalRawData) + { + Image = image; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterImageOutput() + { + } + + /// The image data for the Code Interpreter tool call output. + public RunStepDeltaCodeInterpreterImageOutputObject Image { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.Serialization.cs new file mode 100644 index 000000000000..9d7feaabb742 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.Serialization.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterImageOutputObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutputObject)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(FileId)) + { + writer.WritePropertyName("file_id"u8); + writer.WriteStringValue(FileId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaCodeInterpreterImageOutputObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutputObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterImageOutputObject(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterImageOutputObject DeserializeRunStepDeltaCodeInterpreterImageOutputObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string fileId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_id"u8)) + { + fileId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterImageOutputObject(fileId, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutputObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterImageOutputObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterImageOutputObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterImageOutputObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaCodeInterpreterImageOutputObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterImageOutputObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.cs new file mode 100644 index 000000000000..35c4bf8d080b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterImageOutputObject.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data for a streaming run step's Code Interpreter tool call image output. + public partial class RunStepDeltaCodeInterpreterImageOutputObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaCodeInterpreterImageOutputObject() + { + } + + /// Initializes a new instance of . + /// The file ID for the image. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaCodeInterpreterImageOutputObject(string fileId, IDictionary serializedAdditionalRawData) + { + FileId = fileId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The file ID for the image. + public string FileId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.Serialization.cs new file mode 100644 index 000000000000..b92c96d6348f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.Serialization.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterLogOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterLogOutput)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Logs)) + { + writer.WritePropertyName("logs"u8); + writer.WriteStringValue(Logs); + } + } + + RunStepDeltaCodeInterpreterLogOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterLogOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterLogOutput(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterLogOutput DeserializeRunStepDeltaCodeInterpreterLogOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string logs = default; + int index = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("logs"u8)) + { + logs = property.Value.GetString(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterLogOutput(index, type, serializedAdditionalRawData, logs); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterLogOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterLogOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterLogOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterLogOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaCodeInterpreterLogOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterLogOutput(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.cs new file mode 100644 index 000000000000..96eaa7b38dc3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterLogOutput.cs @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a log output as produced by the Code Interpreter tool and as represented in a streaming run step's delta tool calls collection. + public partial class RunStepDeltaCodeInterpreterLogOutput : RunStepDeltaCodeInterpreterOutput + { + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + internal RunStepDeltaCodeInterpreterLogOutput(int index) : base(index) + { + Type = "logs"; + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + /// The text output from the Code Interpreter tool call. + internal RunStepDeltaCodeInterpreterLogOutput(int index, string type, IDictionary serializedAdditionalRawData, string logs) : base(index, type, serializedAdditionalRawData) + { + Logs = logs; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterLogOutput() + { + } + + /// The text output from the Code Interpreter tool call. + public string Logs { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.Serialization.cs new file mode 100644 index 000000000000..f67acd16276c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.Serialization.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownRunStepDeltaCodeInterpreterOutput))] + public partial class RunStepDeltaCodeInterpreterOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterOutput DeserializeRunStepDeltaCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "image": return RunStepDeltaCodeInterpreterImageOutput.DeserializeRunStepDeltaCodeInterpreterImageOutput(element, options); + case "logs": return RunStepDeltaCodeInterpreterLogOutput.DeserializeRunStepDeltaCodeInterpreterLogOutput(element, options); + } + } + return UnknownRunStepDeltaCodeInterpreterOutput.DeserializeUnknownRunStepDeltaCodeInterpreterOutput(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaCodeInterpreterOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.cs new file mode 100644 index 000000000000..396e993239ce --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterOutput.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a streaming run step tool call's Code Interpreter tool output. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class RunStepDeltaCodeInterpreterOutput + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + protected RunStepDeltaCodeInterpreterOutput(int index) + { + Index = index; + } + + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaCodeInterpreterOutput(int index, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterOutput() + { + } + + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + public int Index { get; } + /// The type of the streaming run step tool call's Code Interpreter output. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.Serialization.cs new file mode 100644 index 000000000000..489f5d289a93 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaCodeInterpreterToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterToolCall)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + } + + RunStepDeltaCodeInterpreterToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterToolCall(document.RootElement, options); + } + + internal static RunStepDeltaCodeInterpreterToolCall DeserializeRunStepDeltaCodeInterpreterToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaCodeInterpreterDetailItemObject codeInterpreter = default; + int index = default; + string id = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = RunStepDeltaCodeInterpreterDetailItemObject.DeserializeRunStepDeltaCodeInterpreterDetailItemObject(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaCodeInterpreterToolCall(index, id, type, serializedAdditionalRawData, codeInterpreter); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaCodeInterpreterToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.cs new file mode 100644 index 000000000000..059c30cbca81 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaCodeInterpreterToolCall.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a Code Interpreter tool call within a streaming run step's tool call details. + public partial class RunStepDeltaCodeInterpreterToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + internal RunStepDeltaCodeInterpreterToolCall(int index, string id) : base(index, id) + { + Argument.AssertNotNull(id, nameof(id)); + + Type = "code_interpreter"; + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + /// The Code Interpreter data for the tool call. + internal RunStepDeltaCodeInterpreterToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData, RunStepDeltaCodeInterpreterDetailItemObject codeInterpreter) : base(index, id, type, serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaCodeInterpreterToolCall() + { + } + + /// The Code Interpreter data for the tool call. + public RunStepDeltaCodeInterpreterDetailItemObject CodeInterpreter { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.Serialization.cs new file mode 100644 index 000000000000..8fad23851a70 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownRunStepDeltaDetail))] + public partial class RunStepDeltaDetail : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaDetail IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaDetail(document.RootElement, options); + } + + internal static RunStepDeltaDetail DeserializeRunStepDeltaDetail(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "message_creation": return RunStepDeltaMessageCreation.DeserializeRunStepDeltaMessageCreation(element, options); + case "tool_calls": return RunStepDeltaToolCallObject.DeserializeRunStepDeltaToolCallObject(element, options); + } + } + return UnknownRunStepDeltaDetail.DeserializeUnknownRunStepDeltaDetail(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaDetail IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaDetail(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaDetail FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaDetail(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.cs new file mode 100644 index 000000000000..508fac38660c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaDetail.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Represents a single run step detail item in a streaming run step's delta payload. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class RunStepDeltaDetail + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected RunStepDeltaDetail() + { + } + + /// Initializes a new instance of . + /// The object type for the run step detail object. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaDetail(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type for the run step detail object. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.Serialization.cs new file mode 100644 index 000000000000..2ef059879d2f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.Serialization.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaFileSearchToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaFileSearchToolCall)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsCollectionDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); + writer.WriteStartObject(); + foreach (var item in FileSearch) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + } + + RunStepDeltaFileSearchToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaFileSearchToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaFileSearchToolCall(document.RootElement, options); + } + + internal static RunStepDeltaFileSearchToolCall DeserializeRunStepDeltaFileSearchToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyDictionary fileSearch = default; + int index = default; + string id = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + fileSearch = dictionary; + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaFileSearchToolCall(index, id, type, serializedAdditionalRawData, fileSearch ?? new ChangeTrackingDictionary()); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaFileSearchToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaFileSearchToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaFileSearchToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaFileSearchToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaFileSearchToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaFileSearchToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.cs new file mode 100644 index 000000000000..7be515d9cc76 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFileSearchToolCall.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a file search tool call within a streaming run step's tool call details. + public partial class RunStepDeltaFileSearchToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + internal RunStepDeltaFileSearchToolCall(int index, string id) : base(index, id) + { + Argument.AssertNotNull(id, nameof(id)); + + Type = "file_search"; + FileSearch = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + /// Reserved for future use. + internal RunStepDeltaFileSearchToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData, IReadOnlyDictionary fileSearch) : base(index, id, type, serializedAdditionalRawData) + { + FileSearch = fileSearch; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaFileSearchToolCall() + { + } + + /// Reserved for future use. + public IReadOnlyDictionary FileSearch { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.Serialization.cs new file mode 100644 index 000000000000..dfd29726c505 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.Serialization.cs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaFunction : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaFunction)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(Arguments)) + { + writer.WritePropertyName("arguments"u8); + writer.WriteStringValue(Arguments); + } + if (Optional.IsDefined(Output)) + { + if (Output != null) + { + writer.WritePropertyName("output"u8); + writer.WriteStringValue(Output); + } + else + { + writer.WriteNull("output"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaFunction)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaFunction(document.RootElement, options); + } + + internal static RunStepDeltaFunction DeserializeRunStepDeltaFunction(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string arguments = default; + string output = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("arguments"u8)) + { + arguments = property.Value.GetString(); + continue; + } + if (property.NameEquals("output"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + output = null; + continue; + } + output = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaFunction(name, arguments, output, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaFunction)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaFunction(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaFunction)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaFunction FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaFunction(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.cs new file mode 100644 index 000000000000..df34c88e6f43 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunction.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the function data in a streaming run step delta's function tool call. + public partial class RunStepDeltaFunction + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaFunction() + { + } + + /// Initializes a new instance of . + /// The name of the function. + /// The arguments passed to the function as input. + /// The output of the function, null if outputs have not yet been submitted. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaFunction(string name, string arguments, string output, IDictionary serializedAdditionalRawData) + { + Name = name; + Arguments = arguments; + Output = output; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The name of the function. + public string Name { get; } + /// The arguments passed to the function as input. + public string Arguments { get; } + /// The output of the function, null if outputs have not yet been submitted. + public string Output { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.Serialization.cs new file mode 100644 index 000000000000..372692e32a75 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaFunctionToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaFunctionToolCall)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(Function)) + { + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } + } + + RunStepDeltaFunctionToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaFunctionToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaFunctionToolCall(document.RootElement, options); + } + + internal static RunStepDeltaFunctionToolCall DeserializeRunStepDeltaFunctionToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaFunction function = default; + int index = default; + string id = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + function = RunStepDeltaFunction.DeserializeRunStepDeltaFunction(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaFunctionToolCall(index, id, type, serializedAdditionalRawData, function); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaFunctionToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaFunctionToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaFunctionToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaFunctionToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaFunctionToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaFunctionToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.cs new file mode 100644 index 000000000000..ce9d9486ef82 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaFunctionToolCall.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a function tool call within a streaming run step's tool call details. + public partial class RunStepDeltaFunctionToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + internal RunStepDeltaFunctionToolCall(int index, string id) : base(index, id) + { + Argument.AssertNotNull(id, nameof(id)); + + Type = "function"; + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + /// The function data for the tool call. + internal RunStepDeltaFunctionToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData, RunStepDeltaFunction function) : base(index, id, type, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaFunctionToolCall() + { + } + + /// The function data for the tool call. + public RunStepDeltaFunction Function { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.Serialization.cs new file mode 100644 index 000000000000..aa98784dc30f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.Serialization.cs @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaMessageCreation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreation)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsDefined(MessageCreation)) + { + writer.WritePropertyName("message_creation"u8); + writer.WriteObjectValue(MessageCreation, options); + } + } + + RunStepDeltaMessageCreation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaMessageCreation(document.RootElement, options); + } + + internal static RunStepDeltaMessageCreation DeserializeRunStepDeltaMessageCreation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + RunStepDeltaMessageCreationObject messageCreation = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("message_creation"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + messageCreation = RunStepDeltaMessageCreationObject.DeserializeRunStepDeltaMessageCreationObject(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaMessageCreation(type, serializedAdditionalRawData, messageCreation); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreation)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaMessageCreation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaMessageCreation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaMessageCreation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaMessageCreation(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.cs new file mode 100644 index 000000000000..38f8a808eeac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreation.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents a message creation within a streaming run step delta. + public partial class RunStepDeltaMessageCreation : RunStepDeltaDetail + { + /// Initializes a new instance of . + internal RunStepDeltaMessageCreation() + { + Type = "message_creation"; + } + + /// Initializes a new instance of . + /// The object type for the run step detail object. + /// Keeps track of any properties unknown to the library. + /// The message creation data. + internal RunStepDeltaMessageCreation(string type, IDictionary serializedAdditionalRawData, RunStepDeltaMessageCreationObject messageCreation) : base(type, serializedAdditionalRawData) + { + MessageCreation = messageCreation; + } + + /// The message creation data. + public RunStepDeltaMessageCreationObject MessageCreation { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.Serialization.cs new file mode 100644 index 000000000000..f25ce59a3ae4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.Serialization.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaMessageCreationObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreationObject)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(MessageId)) + { + writer.WritePropertyName("message_id"u8); + writer.WriteStringValue(MessageId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaMessageCreationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreationObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaMessageCreationObject(document.RootElement, options); + } + + internal static RunStepDeltaMessageCreationObject DeserializeRunStepDeltaMessageCreationObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string messageId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("message_id"u8)) + { + messageId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaMessageCreationObject(messageId, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreationObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaMessageCreationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaMessageCreationObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaMessageCreationObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaMessageCreationObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaMessageCreationObject(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.cs new file mode 100644 index 000000000000..15aaccdbc60c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaMessageCreationObject.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents the data within a streaming run step message creation response object. + public partial class RunStepDeltaMessageCreationObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal RunStepDeltaMessageCreationObject() + { + } + + /// Initializes a new instance of . + /// The ID of the newly-created message. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaMessageCreationObject(string messageId, IDictionary serializedAdditionalRawData) + { + MessageId = messageId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The ID of the newly-created message. + public string MessageId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.Serialization.cs new file mode 100644 index 000000000000..308ee81ccf2f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.Serialization.cs @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownRunStepDeltaToolCall))] + public partial class RunStepDeltaToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + RunStepDeltaToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + + internal static RunStepDeltaToolCall DeserializeRunStepDeltaToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "code_interpreter": return RunStepDeltaCodeInterpreterToolCall.DeserializeRunStepDeltaCodeInterpreterToolCall(element, options); + case "file_search": return RunStepDeltaFileSearchToolCall.DeserializeRunStepDeltaFileSearchToolCall(element, options); + case "function": return RunStepDeltaFunctionToolCall.DeserializeRunStepDeltaFunctionToolCall(element, options); + } + } + return UnknownRunStepDeltaToolCall.DeserializeUnknownRunStepDeltaToolCall(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static RunStepDeltaToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaToolCall(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.cs new file mode 100644 index 000000000000..c056ec5693c5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCall.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// The abstract base representation of a single tool call within a streaming run step's delta tool call details. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class RunStepDeltaToolCall + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// is null. + protected RunStepDeltaToolCall(int index, string id) + { + Argument.AssertNotNull(id, nameof(id)); + + Index = index; + Id = id; + } + + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + internal RunStepDeltaToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData) + { + Index = index; + Id = id; + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal RunStepDeltaToolCall() + { + } + + /// The index of the tool call detail in the run step's tool_calls array. + public int Index { get; } + /// The ID of the tool call, used when submitting outputs to the run. + public string Id { get; } + /// The type of the tool call detail item in a streaming run step's details. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.Serialization.cs new file mode 100644 index 000000000000..8803d2e2754e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.Serialization.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepDeltaToolCallObject : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaToolCallObject)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Optional.IsCollectionDefined(ToolCalls)) + { + writer.WritePropertyName("tool_calls"u8); + writer.WriteStartArray(); + foreach (var item in ToolCalls) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + } + + RunStepDeltaToolCallObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaToolCallObject)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaToolCallObject(document.RootElement, options); + } + + internal static RunStepDeltaToolCallObject DeserializeRunStepDeltaToolCallObject(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList toolCalls = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(RunStepDeltaToolCall.DeserializeRunStepDeltaToolCall(item, options)); + } + toolCalls = array; + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepDeltaToolCallObject(type, serializedAdditionalRawData, toolCalls ?? new ChangeTrackingList()); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCallObject)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaToolCallObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaToolCallObject(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCallObject)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepDeltaToolCallObject FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaToolCallObject(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.cs new file mode 100644 index 000000000000..77d87fe333e1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepDeltaToolCallObject.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Represents an invocation of tool calls as part of a streaming run step. + public partial class RunStepDeltaToolCallObject : RunStepDeltaDetail + { + /// Initializes a new instance of . + internal RunStepDeltaToolCallObject() + { + Type = "tool_calls"; + ToolCalls = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The object type for the run step detail object. + /// Keeps track of any properties unknown to the library. + /// + /// The collection of tool calls for the tool call detail item. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + internal RunStepDeltaToolCallObject(string type, IDictionary serializedAdditionalRawData, IReadOnlyList toolCalls) : base(type, serializedAdditionalRawData) + { + ToolCalls = toolCalls; + } + + /// + /// The collection of tool calls for the tool call detail item. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public IReadOnlyList ToolCalls { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.Serialization.cs new file mode 100644 index 000000000000..083a4df3e845 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class RunStepFileSearchToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("file_search"u8); + writer.WriteStartArray(); + foreach (var item in FileSearch) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + + RunStepFileSearchToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepFileSearchToolCall(document.RootElement, options); + } + + internal static RunStepFileSearchToolCall DeserializeRunStepFileSearchToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList fileSearch = default; + string type = default; + string id = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_search"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FileSearchToolCallResult.DeserializeFileSearchToolCallResult(item, options)); + } + fileSearch = array; + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new RunStepFileSearchToolCall(type, id, serializedAdditionalRawData, fileSearch); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepFileSearchToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepFileSearchToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepFileSearchToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new RunStepFileSearchToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepFileSearchToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.cs new file mode 100644 index 000000000000..23e713b3d2b0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepFileSearchToolCall.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// A record of a call to a file search tool, issued by the model in evaluation of a defined tool, that represents + /// executed file search. + /// + public partial class RunStepFileSearchToolCall : RunStepToolCall + { + /// Initializes a new instance of . + /// The ID of the tool call. This ID must be referenced when you submit tool outputs. + /// The results of the file search. + /// or is null. + internal RunStepFileSearchToolCall(string id, IEnumerable fileSearch) : base(id) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(fileSearch, nameof(fileSearch)); + + Type = "file_search"; + FileSearch = fileSearch.ToList(); + } + + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. This ID must be referenced when you submit tool outputs. + /// Keeps track of any properties unknown to the library. + /// The results of the file search. + internal RunStepFileSearchToolCall(string type, string id, IDictionary serializedAdditionalRawData, IReadOnlyList fileSearch) : base(type, id, serializedAdditionalRawData) + { + FileSearch = fileSearch; + } + + /// Initializes a new instance of for deserialization. + internal RunStepFileSearchToolCall() + { + } + + /// The results of the file search. + public IReadOnlyList FileSearch { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.cs deleted file mode 100644 index 5f119347d5f3..000000000000 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepRetrievalToolCall.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Assistants -{ - /// - /// A record of a call to a retrieval tool, issued by the model in evaluation of a defined tool, that represents - /// executed retrieval actions. - /// - public partial class RunStepRetrievalToolCall : RunStepToolCall - { - /// Initializes a new instance of . - /// The ID of the tool call. This ID must be referenced when you submit tool outputs. - /// The key/value pairs produced by the retrieval tool. - /// or is null. - internal RunStepRetrievalToolCall(string id, IReadOnlyDictionary retrieval) : base(id) - { - Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(retrieval, nameof(retrieval)); - - Type = "retrieval"; - Retrieval = retrieval; - } - - /// Initializes a new instance of . - /// The object type. - /// The ID of the tool call. This ID must be referenced when you submit tool outputs. - /// Keeps track of any properties unknown to the library. - /// The key/value pairs produced by the retrieval tool. - internal RunStepRetrievalToolCall(string type, string id, IDictionary serializedAdditionalRawData, IReadOnlyDictionary retrieval) : base(type, id, serializedAdditionalRawData) - { - Retrieval = retrieval; - } - - /// Initializes a new instance of for deserialization. - internal RunStepRetrievalToolCall() - { - } - - /// The key/value pairs produced by the retrieval tool. - public IReadOnlyDictionary Retrieval { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepStreamEvent.cs new file mode 100644 index 000000000000..3949704709ad --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepStreamEvent.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Run step operation related streaming events. + public readonly partial struct RunStepStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RunStepStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadRunStepCreatedValue = "thread.run.step.created"; + private const string ThreadRunStepInProgressValue = "thread.run.step.in_progress"; + private const string ThreadRunStepDeltaValue = "thread.run.step.delta"; + private const string ThreadRunStepCompletedValue = "thread.run.step.completed"; + private const string ThreadRunStepFailedValue = "thread.run.step.failed"; + private const string ThreadRunStepCancelledValue = "thread.run.step.cancelled"; + private const string ThreadRunStepExpiredValue = "thread.run.step.expired"; + + /// Event sent when a new thread run step is created. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepCreated { get; } = new RunStepStreamEvent(ThreadRunStepCreatedValue); + /// Event sent when a run step moves to `in_progress` status. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepInProgress { get; } = new RunStepStreamEvent(ThreadRunStepInProgressValue); + /// Event sent when a run stepis being streamed. The data of this event is of type RunStepDeltaChunk. + public static RunStepStreamEvent ThreadRunStepDelta { get; } = new RunStepStreamEvent(ThreadRunStepDeltaValue); + /// Event sent when a run step is completed. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepCompleted { get; } = new RunStepStreamEvent(ThreadRunStepCompletedValue); + /// Event sent when a run step fails. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepFailed { get; } = new RunStepStreamEvent(ThreadRunStepFailedValue); + /// Event sent when a run step is cancelled. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepCancelled { get; } = new RunStepStreamEvent(ThreadRunStepCancelledValue); + /// Event sent when a run step is expired. The data of this event is of type RunStep. + public static RunStepStreamEvent ThreadRunStepExpired { get; } = new RunStepStreamEvent(ThreadRunStepExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(RunStepStreamEvent left, RunStepStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RunStepStreamEvent left, RunStepStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RunStepStreamEvent(string value) => new RunStepStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RunStepStreamEvent other && Equals(other); + /// + public bool Equals(RunStepStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs index 3f2722881b5f..59eb0aae5583 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.Serialization.cs @@ -80,8 +80,8 @@ internal static RunStepToolCall DeserializeRunStepToolCall(JsonElement element, switch (discriminator.GetString()) { case "code_interpreter": return RunStepCodeInterpreterToolCall.DeserializeRunStepCodeInterpreterToolCall(element, options); + case "file_search": return RunStepFileSearchToolCall.DeserializeRunStepFileSearchToolCall(element, options); case "function": return RunStepFunctionToolCall.DeserializeRunStepFunctionToolCall(element, options); - case "retrieval": return RunStepRetrievalToolCall.DeserializeRunStepRetrievalToolCall(element, options); } } return UnknownRunStepToolCall.DeserializeUnknownRunStepToolCall(element, options); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs index a1f39c74d40e..b458fd4827e9 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCall.cs @@ -13,7 +13,7 @@ namespace Azure.AI.OpenAI.Assistants /// /// An abstract representation of a detailed tool call as recorded within a run step for an existing run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public abstract partial class RunStepToolCall { diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs index dedd295f4d8a..1d55d40ac096 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStepToolCallDetails.cs @@ -18,7 +18,7 @@ public partial class RunStepToolCallDetails : RunStepDetails /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// /// is null. internal RunStepToolCallDetails(IEnumerable toolCalls) @@ -35,7 +35,7 @@ internal RunStepToolCallDetails(IEnumerable toolCalls) /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// internal RunStepToolCallDetails(RunStepType type, IDictionary serializedAdditionalRawData, IReadOnlyList toolCalls) : base(type, serializedAdditionalRawData) { @@ -50,7 +50,7 @@ internal RunStepToolCallDetails() /// /// A list of tool call details for this run step. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IReadOnlyList ToolCalls { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStreamEvent.cs new file mode 100644 index 000000000000..d9ce800c9594 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RunStreamEvent.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Run operation related streaming events. + public readonly partial struct RunStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public RunStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadRunCreatedValue = "thread.run.created"; + private const string ThreadRunQueuedValue = "thread.run.queued"; + private const string ThreadRunInProgressValue = "thread.run.in_progress"; + private const string ThreadRunRequiresActionValue = "thread.run.requires_action"; + private const string ThreadRunCompletedValue = "thread.run.completed"; + private const string ThreadRunFailedValue = "thread.run.failed"; + private const string ThreadRunCancellingValue = "thread.run.cancelling"; + private const string ThreadRunCancelledValue = "thread.run.cancelled"; + private const string ThreadRunExpiredValue = "thread.run.expired"; + + /// Event sent when a new run is created. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCreated { get; } = new RunStreamEvent(ThreadRunCreatedValue); + /// Event sent when a run moves to `queued` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunQueued { get; } = new RunStreamEvent(ThreadRunQueuedValue); + /// Event sent when a run moves to `in_progress` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunInProgress { get; } = new RunStreamEvent(ThreadRunInProgressValue); + /// Event sent when a run moves to `requires_action` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunRequiresAction { get; } = new RunStreamEvent(ThreadRunRequiresActionValue); + /// Event sent when a run is completed. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCompleted { get; } = new RunStreamEvent(ThreadRunCompletedValue); + /// Event sent when a run fails. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunFailed { get; } = new RunStreamEvent(ThreadRunFailedValue); + /// Event sent when a run moves to `cancelling` status. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCancelling { get; } = new RunStreamEvent(ThreadRunCancellingValue); + /// Event sent when a run is cancelled. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunCancelled { get; } = new RunStreamEvent(ThreadRunCancelledValue); + /// Event sent when a run is expired. The data of this event is of type ThreadRun. + public static RunStreamEvent ThreadRunExpired { get; } = new RunStreamEvent(ThreadRunExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(RunStreamEvent left, RunStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(RunStreamEvent left, RunStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator RunStreamEvent(string value) => new RunStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is RunStreamEvent other && Equals(other); + /// + public bool Equals(RunStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs index 578385488318..3c283ee481a9 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.Serialization.cs @@ -41,6 +41,18 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteObjectValue(item, options); } writer.WriteEndArray(); + if (Optional.IsDefined(Stream)) + { + if (Stream != null) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(Stream.Value); + } + else + { + writer.WriteNull("stream"); + } + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -79,6 +91,7 @@ internal static SubmitToolOutputsToRunRequest DeserializeSubmitToolOutputsToRunR return null; } IReadOnlyList toolOutputs = default; + bool? stream = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -93,13 +106,23 @@ internal static SubmitToolOutputsToRunRequest DeserializeSubmitToolOutputsToRunR toolOutputs = array; continue; } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + stream = null; + continue; + } + stream = property.Value.GetBoolean(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new SubmitToolOutputsToRunRequest(toolOutputs, serializedAdditionalRawData); + return new SubmitToolOutputsToRunRequest(toolOutputs, stream, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs index 7fc21ab959a6..2971598450d1 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/SubmitToolOutputsToRunRequest.cs @@ -47,7 +47,7 @@ internal partial class SubmitToolOutputsToRunRequest private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// The list of tool outputs requested by tool calls from the specified run. + /// A list of tools for which the outputs are being submitted. /// is null. internal SubmitToolOutputsToRunRequest(IEnumerable toolOutputs) { @@ -57,11 +57,13 @@ internal SubmitToolOutputsToRunRequest(IEnumerable toolOutputs) } /// Initializes a new instance of . - /// The list of tool outputs requested by tool calls from the specified run. + /// A list of tools for which the outputs are being submitted. + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. /// Keeps track of any properties unknown to the library. - internal SubmitToolOutputsToRunRequest(IReadOnlyList toolOutputs, IDictionary serializedAdditionalRawData) + internal SubmitToolOutputsToRunRequest(IReadOnlyList toolOutputs, bool? stream, IDictionary serializedAdditionalRawData) { ToolOutputs = toolOutputs; + Stream = stream; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -70,7 +72,9 @@ internal SubmitToolOutputsToRunRequest() { } - /// The list of tool outputs requested by tool calls from the specified run. + /// A list of tools for which the outputs are being submitted. public IReadOnlyList ToolOutputs { get; } + /// If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + public bool? Stream { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs index c76a75916857..f83443bb45a0 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.Serialization.cs @@ -42,6 +42,35 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteNumberValue(CreatedAt, "U"); writer.WritePropertyName("thread_id"u8); writer.WriteStringValue(ThreadId); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (IncompleteDetails != null) + { + writer.WritePropertyName("incomplete_details"u8); + writer.WriteObjectValue(IncompleteDetails, options); + } + else + { + writer.WriteNull("incomplete_details"); + } + if (CompletedAt != null) + { + writer.WritePropertyName("completed_at"u8); + writer.WriteNumberValue(CompletedAt.Value, "U"); + } + else + { + writer.WriteNull("completed_at"); + } + if (IncompleteAt != null) + { + writer.WritePropertyName("incomplete_at"u8); + writer.WriteNumberValue(IncompleteAt.Value, "U"); + } + else + { + writer.WriteNull("incomplete_at"); + } writer.WritePropertyName("role"u8); writer.WriteStringValue(Role.ToString()); writer.WritePropertyName("content"u8); @@ -51,23 +80,38 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteObjectValue(item, options); } writer.WriteEndArray(); - if (Optional.IsDefined(AssistantId)) + if (AssistantId != null) { writer.WritePropertyName("assistant_id"u8); writer.WriteStringValue(AssistantId); } - if (Optional.IsDefined(RunId)) + else + { + writer.WriteNull("assistant_id"); + } + if (RunId != null) { writer.WritePropertyName("run_id"u8); writer.WriteStringValue(RunId); } - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + else { - writer.WriteStringValue(item); + writer.WriteNull("run_id"); + } + if (Attachments != null && Optional.IsCollectionDefined(Attachments)) + { + writer.WritePropertyName("attachments"u8); + writer.WriteStartArray(); + foreach (var item in Attachments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("attachments"); } - writer.WriteEndArray(); if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -124,12 +168,16 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode string @object = default; DateTimeOffset createdAt = default; string threadId = default; + MessageStatus status = default; + MessageIncompleteDetails incompleteDetails = default; + DateTimeOffset? completedAt = default; + DateTimeOffset? incompleteAt = default; MessageRole role = default; - IReadOnlyList content = default; + IList content = default; string assistantId = default; string runId = default; - IReadOnlyList fileIds = default; - IReadOnlyDictionary metadata = default; + IList attachments = default; + IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -154,6 +202,41 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode threadId = property.Value.GetString(); continue; } + if (property.NameEquals("status"u8)) + { + status = new MessageStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("incomplete_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + incompleteDetails = null; + continue; + } + incompleteDetails = MessageIncompleteDetails.DeserializeMessageIncompleteDetails(property.Value, options); + continue; + } + if (property.NameEquals("completed_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + completedAt = null; + continue; + } + completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("incomplete_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + incompleteAt = null; + continue; + } + incompleteAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } if (property.NameEquals("role"u8)) { role = new MessageRole(property.Value.GetString()); @@ -171,22 +254,37 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode } if (property.NameEquals("assistant_id"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + assistantId = null; + continue; + } assistantId = property.Value.GetString(); continue; } if (property.NameEquals("run_id"u8)) { + if (property.Value.ValueKind == JsonValueKind.Null) + { + runId = null; + continue; + } runId = property.Value.GetString(); continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("attachments"u8)) { - List array = new List(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + attachments = new ChangeTrackingList(); + continue; + } + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(MessageAttachment.DeserializeMessageAttachment(item, options)); } - fileIds = array; + attachments = array; continue; } if (property.NameEquals("metadata"u8)) @@ -215,11 +313,15 @@ internal static ThreadMessage DeserializeThreadMessage(JsonElement element, Mode @object, createdAt, threadId, + status, + incompleteDetails, + completedAt, + incompleteAt, role, content, assistantId, runId, - fileIds, + attachments, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs index 8bc5a7e7779b..c730b23b4dcf 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessage.cs @@ -50,31 +50,39 @@ public partial class ThreadMessage /// The identifier, which can be referenced in API endpoints. /// The Unix timestamp, in seconds, representing when this object was created. /// The ID of the thread that this message belongs to. + /// The status of the message. + /// On an incomplete message, details about why the message is incomplete. + /// The Unix timestamp (in seconds) for when the message was completed. + /// The Unix timestamp (in seconds) for when the message was marked as incomplete. /// The role associated with the assistant thread message. /// /// The list of content items associated with the assistant thread message. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. /// The available derived classes include and . /// - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. - /// + /// If applicable, the ID of the assistant that authored this message. + /// If applicable, the ID of the run associated with the authoring of this message. + /// A list of files attached to the message, and the tools they were added to. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// , , or is null. - internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, MessageRole role, IEnumerable contentItems, IEnumerable fileIds, IReadOnlyDictionary metadata) + /// , or is null. + public ThreadMessage(string id, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageIncompleteDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, MessageRole role, IEnumerable contentItems, string assistantId, string runId, IEnumerable attachments, IDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(threadId, nameof(threadId)); Argument.AssertNotNull(contentItems, nameof(contentItems)); - Argument.AssertNotNull(fileIds, nameof(fileIds)); Id = id; CreatedAt = createdAt; ThreadId = threadId; + Status = status; + IncompleteDetails = incompleteDetails; + CompletedAt = completedAt; + IncompleteAt = incompleteAt; Role = role; ContentItems = contentItems.ToList(); - FileIds = fileIds.ToList(); + AssistantId = assistantId; + RunId = runId; + Attachments = attachments?.ToList(); Metadata = metadata; } @@ -83,6 +91,10 @@ internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, Mes /// The object type, which is always 'thread.message'. /// The Unix timestamp, in seconds, representing when this object was created. /// The ID of the thread that this message belongs to. + /// The status of the message. + /// On an incomplete message, details about why the message is incomplete. + /// The Unix timestamp (in seconds) for when the message was completed. + /// The Unix timestamp (in seconds) for when the message was marked as incomplete. /// The role associated with the assistant thread message. /// /// The list of content items associated with the assistant thread message. @@ -91,23 +103,24 @@ internal ThreadMessage(string id, DateTimeOffset createdAt, string threadId, Mes /// /// If applicable, the ID of the assistant that authored this message. /// If applicable, the ID of the run associated with the authoring of this message. - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. - /// + /// A list of files attached to the message, and the tools they were added to. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal ThreadMessage(string id, string @object, DateTimeOffset createdAt, string threadId, MessageRole role, IReadOnlyList contentItems, string assistantId, string runId, IReadOnlyList fileIds, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadMessage(string id, string @object, DateTimeOffset createdAt, string threadId, MessageStatus status, MessageIncompleteDetails incompleteDetails, DateTimeOffset? completedAt, DateTimeOffset? incompleteAt, MessageRole role, IList contentItems, string assistantId, string runId, IList attachments, IDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; CreatedAt = createdAt; ThreadId = threadId; + Status = status; + IncompleteDetails = incompleteDetails; + CompletedAt = completedAt; + IncompleteAt = incompleteAt; Role = role; ContentItems = contentItems; AssistantId = assistantId; RunId = runId; - FileIds = fileIds; + Attachments = attachments; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -118,30 +131,35 @@ internal ThreadMessage() } /// The identifier, which can be referenced in API endpoints. - public string Id { get; } + public string Id { get; set; } /// The Unix timestamp, in seconds, representing when this object was created. - public DateTimeOffset CreatedAt { get; } + public DateTimeOffset CreatedAt { get; set; } /// The ID of the thread that this message belongs to. - public string ThreadId { get; } + public string ThreadId { get; set; } + /// The status of the message. + public MessageStatus Status { get; set; } + /// On an incomplete message, details about why the message is incomplete. + public MessageIncompleteDetails IncompleteDetails { get; set; } + /// The Unix timestamp (in seconds) for when the message was completed. + public DateTimeOffset? CompletedAt { get; set; } + /// The Unix timestamp (in seconds) for when the message was marked as incomplete. + public DateTimeOffset? IncompleteAt { get; set; } /// The role associated with the assistant thread message. - public MessageRole Role { get; } + public MessageRole Role { get; set; } /// /// The list of content items associated with the assistant thread message. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. /// The available derived classes include and . /// - public IReadOnlyList ContentItems { get; } + public IList ContentItems { get; } /// If applicable, the ID of the assistant that authored this message. - public string AssistantId { get; } + public string AssistantId { get; set; } /// If applicable, the ID of the run associated with the authoring of this message. - public string RunId { get; } - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. - /// - public IReadOnlyList FileIds { get; } + public string RunId { get; set; } + /// A list of files attached to the message, and the tools they were added to. + public IList Attachments { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - public IReadOnlyDictionary Metadata { get; } + public IDictionary Metadata { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.Serialization.cs similarity index 70% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.Serialization.cs index b8cd2cbf423c..80dd17220a50 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class CreateMessageRequest : IUtf8JsonSerializable, IJsonModel + public partial class ThreadMessageOptions : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,25 +28,32 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWr /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateMessageRequest)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support writing '{format}' format."); } writer.WritePropertyName("role"u8); writer.WriteStringValue(Role.ToString()); writer.WritePropertyName("content"u8); writer.WriteStringValue(Content); - if (Optional.IsCollectionDefined(FileIds)) + if (Optional.IsCollectionDefined(Attachments)) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + if (Attachments != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("attachments"u8); + writer.WriteStartArray(); + foreach (var item in Attachments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("attachments"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -83,19 +90,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - CreateMessageRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ThreadMessageOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateMessageRequest)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateMessageRequest(document.RootElement, options); + return DeserializeThreadMessageOptions(document.RootElement, options); } - internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static ThreadMessageOptions DeserializeThreadMessageOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -105,8 +112,8 @@ internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement } MessageRole role = default; string content = default; - IReadOnlyList fileIds = default; - IReadOnlyDictionary metadata = default; + IList attachments = default; + IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -121,18 +128,18 @@ internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement content = property.Value.GetString(); continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("attachments"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); + List array = new List(); foreach (var item in property.Value.EnumerateArray()) { - array.Add(item.GetString()); + array.Add(MessageAttachment.DeserializeMessageAttachment(item, options)); } - fileIds = array; + attachments = array; continue; } if (property.NameEquals("metadata"u8)) @@ -155,46 +162,46 @@ internal static CreateMessageRequest DeserializeCreateMessageRequest(JsonElement } } serializedAdditionalRawData = rawDataDictionary; - return new CreateMessageRequest(role, content, fileIds ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new ThreadMessageOptions(role, content, attachments ?? new ChangeTrackingList(), metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(CreateMessageRequest)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support writing '{options.Format}' format."); } } - CreateMessageRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ThreadMessageOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateMessageRequest(document.RootElement, options); + return DeserializeThreadMessageOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateMessageRequest)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ThreadMessageOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateMessageRequest FromResponse(Response response) + internal static ThreadMessageOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateMessageRequest(document.RootElement); + return DeserializeThreadMessageOptions(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.cs similarity index 53% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.cs index 5ce61588505d..6487c1ad7bf4 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadInitializationMessage.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadMessageOptions.cs @@ -11,7 +11,7 @@ namespace Azure.AI.OpenAI.Assistants { /// A single message within an assistant thread, as provided during that thread's creation for its initial state. - public partial class ThreadInitializationMessage + public partial class ThreadMessageOptions { /// /// Keeps track of any properties unknown to the library. @@ -45,52 +45,70 @@ public partial class ThreadInitializationMessage /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. + /// Initializes a new instance of . + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. + /// + /// + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. + /// /// is null. - public ThreadInitializationMessage(MessageRole role, string content) + public ThreadMessageOptions(MessageRole role, string content) { Argument.AssertNotNull(content, nameof(content)); Role = role; Content = content; - FileIds = new ChangeTrackingList(); + Attachments = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } - /// Initializes a new instance of . - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. - /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. + /// Initializes a new instance of . + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. /// + /// + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. + /// + /// A list of files attached to the message, and the tools they should be added to. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal ThreadInitializationMessage(MessageRole role, string content, IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadMessageOptions(MessageRole role, string content, IList attachments, IDictionary metadata, IDictionary serializedAdditionalRawData) { Role = role; Content = content; - FileIds = fileIds; + Attachments = attachments; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal ThreadInitializationMessage() + /// Initializes a new instance of for deserialization. + internal ThreadMessageOptions() { } - /// The role associated with the assistant thread message. Currently, only 'user' is supported when providing initial messages to a new thread. + /// + /// The role of the entity that is creating the message. Allowed values include: + /// - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages. + /// - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into + /// the conversation. + /// public MessageRole Role { get; } - /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via a separate call to the create message API. - public string Content { get; } /// - /// A list of file IDs that the assistant should use. Useful for tools like retrieval and code_interpreter that can - /// access files. + /// The textual content of the initial message. Currently, robust input including images and annotated text may only be provided via + /// a separate call to the create message API. /// - public IList FileIds { get; } + public string Content { get; } + /// A list of files attached to the message, and the tools they should be added to. + public IList Attachments { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs index e9eeb6a58e88..fb70c33b0349 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.Serialization.cs @@ -76,13 +76,6 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteObjectValue(item, options); } writer.WriteEndArray(); - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) - { - writer.WriteStringValue(item); - } - writer.WriteEndArray(); writer.WritePropertyName("created_at"u8); writer.WriteNumberValue(CreatedAt, "U"); if (ExpiresAt != null) @@ -130,6 +123,109 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit { writer.WriteNull("failed_at"); } + if (IncompleteDetails != null) + { + writer.WritePropertyName("incomplete_details"u8); + writer.WriteStringValue(IncompleteDetails.Value.ToString()); + } + else + { + writer.WriteNull("incomplete_details"); + } + if (Usage != null) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + else + { + writer.WriteNull("usage"); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (MaxPromptTokens != null) + { + writer.WritePropertyName("max_prompt_tokens"u8); + writer.WriteNumberValue(MaxPromptTokens.Value); + } + else + { + writer.WriteNull("max_prompt_tokens"); + } + if (MaxCompletionTokens != null) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + else + { + writer.WriteNull("max_completion_tokens"); + } + if (TruncationStrategy != null) + { + writer.WritePropertyName("truncation_strategy"u8); + writer.WriteObjectValue(TruncationStrategy, options); + } + else + { + writer.WriteNull("truncation_strategy"); + } + if (ToolChoice != null) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("tool_choice"); + } + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls); + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); + } if (Metadata != null && Optional.IsCollectionDefined(Metadata)) { writer.WritePropertyName("metadata"u8); @@ -192,13 +288,22 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW string model = default; string instructions = default; IReadOnlyList tools = default; - IReadOnlyList fileIds = default; DateTimeOffset createdAt = default; DateTimeOffset? expiresAt = default; DateTimeOffset? startedAt = default; DateTimeOffset? completedAt = default; DateTimeOffset? cancelledAt = default; DateTimeOffset? failedAt = default; + IncompleteRunDetails? incompleteDetails = default; + RunCompletionUsage usage = default; + float? temperature = default; + float? topP = default; + int? maxPromptTokens = default; + int? maxCompletionTokens = default; + TruncationObject truncationStrategy = default; + BinaryData toolChoice = default; + bool parallelToolCalls = default; + BinaryData responseFormat = default; IReadOnlyDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -269,16 +374,6 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW tools = array; continue; } - if (property.NameEquals("file_ids"u8)) - { - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) - { - array.Add(item.GetString()); - } - fileIds = array; - continue; - } if (property.NameEquals("created_at"u8)) { createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); @@ -309,6 +404,101 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW DeserializeNullableDateTimeOffset(property, ref failedAt); continue; } + if (property.NameEquals("incomplete_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + incompleteDetails = null; + continue; + } + incompleteDetails = new IncompleteRunDetails(property.Value.GetString()); + continue; + } + if (property.NameEquals("usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + usage = null; + continue; + } + usage = RunCompletionUsage.DeserializeRunCompletionUsage(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("max_prompt_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxPromptTokens = null; + continue; + } + maxPromptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + maxCompletionTokens = null; + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("truncation_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + truncationStrategy = null; + continue; + } + truncationStrategy = TruncationObject.DeserializeTruncationObject(property.Value, options); + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolChoice = null; + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("parallel_tool_calls"u8)) + { + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; + } + responseFormat = BinaryData.FromString(property.Value.GetRawText()); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -341,13 +531,22 @@ internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderW model, instructions, tools, - fileIds, createdAt, expiresAt, startedAt, completedAt, cancelledAt, failedAt, + incompleteDetails, + usage, + temperature, + topP, + maxPromptTokens, + maxCompletionTokens, + truncationStrategy, + toolChoice, + parallelToolCalls, + responseFormat, metadata, serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs index 31c97e45b559..16b96c0084e0 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadRun.cs @@ -57,18 +57,25 @@ public partial class ThreadRun /// /// The overridden enabled tools used for this assistant thread run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of attached file IDs, ordered by creation date in ascending order. /// The Unix timestamp, in seconds, representing when this object was created. /// The Unix timestamp, in seconds, representing when this item expires. /// The Unix timestamp, in seconds, representing when this item was started. /// The Unix timestamp, in seconds, representing when this completed. /// The Unix timestamp, in seconds, representing when this was cancelled. /// The Unix timestamp, in seconds, representing when this failed. + /// Details on why the run is incomplete. Will be `null` if the run is not incomplete. + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + /// The maximum number of prompt tokens specified to have been used over the course of the run. + /// The maximum number of completion tokens specified to have been used over the course of the run. + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Whether to enable parallel function calling during tool use. + /// The response format of the tool calls used in this run. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - /// , , , , , or is null. - internal ThreadRun(string id, string threadId, string assistantId, RunStatus status, RunError lastError, string model, string instructions, IEnumerable tools, IEnumerable fileIds, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IReadOnlyDictionary metadata) + /// , , , , or is null. + internal ThreadRun(string id, string threadId, string assistantId, RunStatus status, RunError lastError, string model, string instructions, IEnumerable tools, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IncompleteRunDetails? incompleteDetails, RunCompletionUsage usage, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, bool parallelToolCalls, BinaryData responseFormat, IReadOnlyDictionary metadata) { Argument.AssertNotNull(id, nameof(id)); Argument.AssertNotNull(threadId, nameof(threadId)); @@ -76,7 +83,6 @@ internal ThreadRun(string id, string threadId, string assistantId, RunStatus sta Argument.AssertNotNull(model, nameof(model)); Argument.AssertNotNull(instructions, nameof(instructions)); Argument.AssertNotNull(tools, nameof(tools)); - Argument.AssertNotNull(fileIds, nameof(fileIds)); Id = id; ThreadId = threadId; @@ -86,13 +92,20 @@ internal ThreadRun(string id, string threadId, string assistantId, RunStatus sta Model = model; Instructions = instructions; Tools = tools.ToList(); - FileIds = fileIds.ToList(); CreatedAt = createdAt; ExpiresAt = expiresAt; StartedAt = startedAt; CompletedAt = completedAt; CancelledAt = cancelledAt; FailedAt = failedAt; + IncompleteDetails = incompleteDetails; + Usage = usage; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ParallelToolCalls = parallelToolCalls; + ResponseFormat = responseFormat; Metadata = metadata; } @@ -113,18 +126,27 @@ internal ThreadRun(string id, string threadId, string assistantId, RunStatus sta /// /// The overridden enabled tools used for this assistant thread run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// A list of attached file IDs, ordered by creation date in ascending order. /// The Unix timestamp, in seconds, representing when this object was created. /// The Unix timestamp, in seconds, representing when this item expires. /// The Unix timestamp, in seconds, representing when this item was started. /// The Unix timestamp, in seconds, representing when this completed. /// The Unix timestamp, in seconds, representing when this was cancelled. /// The Unix timestamp, in seconds, representing when this failed. + /// Details on why the run is incomplete. Will be `null` if the run is not incomplete. + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + /// The sampling temperature used for this run. If not set, defaults to 1. + /// The nucleus sampling value used for this run. If not set, defaults to 1. + /// The maximum number of prompt tokens specified to have been used over the course of the run. + /// The maximum number of completion tokens specified to have been used over the course of the run. + /// The strategy to use for dropping messages as the context windows moves forward. + /// Controls whether or not and which tool is called by the model. + /// Whether to enable parallel function calling during tool use. + /// The response format of the tool calls used in this run. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal ThreadRun(string id, string @object, string threadId, string assistantId, RunStatus status, RequiredAction requiredAction, RunError lastError, string model, string instructions, IReadOnlyList tools, IReadOnlyList fileIds, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal ThreadRun(string id, string @object, string threadId, string assistantId, RunStatus status, RequiredAction requiredAction, RunError lastError, string model, string instructions, IReadOnlyList tools, DateTimeOffset createdAt, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? completedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, IncompleteRunDetails? incompleteDetails, RunCompletionUsage usage, float? temperature, float? topP, int? maxPromptTokens, int? maxCompletionTokens, TruncationObject truncationStrategy, BinaryData toolChoice, bool parallelToolCalls, BinaryData responseFormat, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) { Id = id; Object = @object; @@ -136,13 +158,22 @@ internal ThreadRun(string id, string @object, string threadId, string assistantI Model = model; Instructions = instructions; Tools = tools; - FileIds = fileIds; CreatedAt = createdAt; ExpiresAt = expiresAt; StartedAt = startedAt; CompletedAt = completedAt; CancelledAt = cancelledAt; FailedAt = failedAt; + IncompleteDetails = incompleteDetails; + Usage = usage; + Temperature = temperature; + TopP = topP; + MaxPromptTokens = maxPromptTokens; + MaxCompletionTokens = maxCompletionTokens; + TruncationStrategy = truncationStrategy; + ToolChoice = toolChoice; + ParallelToolCalls = parallelToolCalls; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -176,11 +207,9 @@ internal ThreadRun() /// /// The overridden enabled tools used for this assistant thread run. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IReadOnlyList Tools { get; } - /// A list of attached file IDs, ordered by creation date in ascending order. - public IReadOnlyList FileIds { get; } /// The Unix timestamp, in seconds, representing when this object was created. public DateTimeOffset CreatedAt { get; } /// The Unix timestamp, in seconds, representing when this item expires. @@ -193,6 +222,112 @@ internal ThreadRun() public DateTimeOffset? CancelledAt { get; } /// The Unix timestamp, in seconds, representing when this failed. public DateTimeOffset? FailedAt { get; } + /// Details on why the run is incomplete. Will be `null` if the run is not incomplete. + public IncompleteRunDetails? IncompleteDetails { get; } + /// Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). + public RunCompletionUsage Usage { get; } + /// The sampling temperature used for this run. If not set, defaults to 1. + public float? Temperature { get; } + /// The nucleus sampling value used for this run. If not set, defaults to 1. + public float? TopP { get; } + /// The maximum number of prompt tokens specified to have been used over the course of the run. + public int? MaxPromptTokens { get; } + /// The maximum number of completion tokens specified to have been used over the course of the run. + public int? MaxCompletionTokens { get; } + /// The strategy to use for dropping messages as the context windows moves forward. + public TruncationObject TruncationStrategy { get; } + /// + /// Controls whether or not and which tool is called by the model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; } + /// Whether to enable parallel function calling during tool use. + public bool ParallelToolCalls { get; } + /// + /// The response format of the tool calls used in this run. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IReadOnlyDictionary Metadata { get; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadStreamEvent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadStreamEvent.cs new file mode 100644 index 000000000000..172bd6c20d99 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ThreadStreamEvent.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Thread operation related streaming events. + public readonly partial struct ThreadStreamEvent : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ThreadStreamEvent(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ThreadCreatedValue = "thread.created"; + + /// Event sent when a new thread is created. The data of this event is of type AssistantThread. + public static ThreadStreamEvent ThreadCreated { get; } = new ThreadStreamEvent(ThreadCreatedValue); + /// Determines if two values are the same. + public static bool operator ==(ThreadStreamEvent left, ThreadStreamEvent right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ThreadStreamEvent left, ThreadStreamEvent right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ThreadStreamEvent(string value) => new ThreadStreamEvent(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ThreadStreamEvent other && Equals(other); + /// + public bool Equals(ThreadStreamEvent other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs index 94299b574576..17a5b3bc41b5 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.Serialization.cs @@ -78,8 +78,8 @@ internal static ToolDefinition DeserializeToolDefinition(JsonElement element, Mo switch (discriminator.GetString()) { case "code_interpreter": return CodeInterpreterToolDefinition.DeserializeCodeInterpreterToolDefinition(element, options); + case "file_search": return FileSearchToolDefinition.DeserializeFileSearchToolDefinition(element, options); case "function": return FunctionToolDefinition.DeserializeFunctionToolDefinition(element, options); - case "retrieval": return RetrievalToolDefinition.DeserializeRetrievalToolDefinition(element, options); } } return UnknownToolDefinition.DeserializeUnknownToolDefinition(element, options); diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs index b9d063fe1c0c..be4c9b0d6cbf 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolDefinition.cs @@ -13,7 +13,7 @@ namespace Azure.AI.OpenAI.Assistants /// /// An abstract representation of an input tool definition that an assistant can use. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public abstract partial class ToolDefinition { diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.Serialization.cs new file mode 100644 index 000000000000..a2e53c705354 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.Serialization.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class ToolResources : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ToolResources)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + if (Optional.IsDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); + writer.WriteObjectValue(FileSearch, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ToolResources IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ToolResources)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeToolResources(document.RootElement, options); + } + + internal static ToolResources DeserializeToolResources(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + CodeInterpreterToolResource codeInterpreter = default; + FileSearchToolResource fileSearch = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = CodeInterpreterToolResource.DeserializeCodeInterpreterToolResource(property.Value, options); + continue; + } + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = FileSearchToolResource.DeserializeFileSearchToolResource(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ToolResources(codeInterpreter, fileSearch, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ToolResources)} does not support writing '{options.Format}' format."); + } + } + + ToolResources IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeToolResources(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ToolResources)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ToolResources FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeToolResources(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.cs new file mode 100644 index 000000000000..408316763e48 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/ToolResources.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of + /// tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` + /// tool requires a list of vector store IDs. + /// + public partial class ToolResources + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ToolResources() + { + } + + /// Initializes a new instance of . + /// Resources to be used by the `code_interpreter tool` consisting of file IDs. + /// Resources to be used by the `file_search` tool consisting of vector store IDs. + /// Keeps track of any properties unknown to the library. + internal ToolResources(CodeInterpreterToolResource codeInterpreter, FileSearchToolResource fileSearch, IDictionary serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + FileSearch = fileSearch; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Resources to be used by the `code_interpreter tool` consisting of file IDs. + public CodeInterpreterToolResource CodeInterpreter { get; } + /// Resources to be used by the `file_search` tool consisting of vector store IDs. + public FileSearchToolResource FileSearch { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.Serialization.cs similarity index 58% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.Serialization.cs index 3a81222297b3..a4ef2894100f 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/AuditRequestInfo.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI.Assistants { - public partial class AuditRequestInfo : IUtf8JsonSerializable, IJsonModel + public partial class TruncationObject : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,27 +28,25 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriter /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(TruncationObject)} does not support writing '{format}' format."); } - writer.WritePropertyName("url"u8); - writer.WriteStringValue(Url); - writer.WritePropertyName("method"u8); - writer.WriteStringValue(Method); - if (Optional.IsDefined(ContentLength)) + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (Optional.IsDefined(LastMessages)) { - writer.WritePropertyName("contentLength"u8); - writer.WriteNumberValue(ContentLength.Value); - } - writer.WritePropertyName("contentType"u8); - writer.WriteStringValue(ContentType); - if (Optional.IsDefined(UserAgent)) - { - writer.WritePropertyName("userAgent"u8); - writer.WriteStringValue(UserAgent); + if (LastMessages != null) + { + writer.WritePropertyName("last_messages"u8); + writer.WriteNumberValue(LastMessages.Value); + } + else + { + writer.WriteNull("last_messages"); + } } if (options.Format != "W" && _serializedAdditionalRawData != null) { @@ -67,19 +65,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - AuditRequestInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + TruncationObject IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(TruncationObject)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAuditRequestInfo(document.RootElement, options); + return DeserializeTruncationObject(document.RootElement, options); } - internal static AuditRequestInfo DeserializeAuditRequestInfo(JsonElement element, ModelReaderWriterOptions options = null) + internal static TruncationObject DeserializeTruncationObject(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -87,42 +85,25 @@ internal static AuditRequestInfo DeserializeAuditRequestInfo(JsonElement element { return null; } - string url = default; - string method = default; - long? contentLength = default; - string contentType = default; - string userAgent = default; + TruncationStrategy type = default; + int? lastMessages = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("url"u8)) + if (property.NameEquals("type"u8)) { - url = property.Value.GetString(); + type = new TruncationStrategy(property.Value.GetString()); continue; } - if (property.NameEquals("method"u8)) - { - method = property.Value.GetString(); - continue; - } - if (property.NameEquals("contentLength"u8)) + if (property.NameEquals("last_messages"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { + lastMessages = null; continue; } - contentLength = property.Value.GetInt64(); - continue; - } - if (property.NameEquals("contentType"u8)) - { - contentType = property.Value.GetString(); - continue; - } - if (property.NameEquals("userAgent"u8)) - { - userAgent = property.Value.GetString(); + lastMessages = property.Value.GetInt32(); continue; } if (options.Format != "W") @@ -131,52 +112,46 @@ internal static AuditRequestInfo DeserializeAuditRequestInfo(JsonElement element } } serializedAdditionalRawData = rawDataDictionary; - return new AuditRequestInfo( - url, - method, - contentLength, - contentType, - userAgent, - serializedAdditionalRawData); + return new TruncationObject(type, lastMessages, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(TruncationObject)} does not support writing '{options.Format}' format."); } } - AuditRequestInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + TruncationObject IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditRequestInfo(document.RootElement, options); + return DeserializeTruncationObject(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(AuditRequestInfo)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(TruncationObject)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static AuditRequestInfo FromResponse(Response response) + internal static TruncationObject FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAuditRequestInfo(document.RootElement); + return DeserializeTruncationObject(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.cs new file mode 100644 index 000000000000..a662e1b7761f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationObject.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Controls for how a thread will be truncated prior to the run. Use this to control the initial + /// context window of the run. + /// + public partial class TruncationObject + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will + /// be truncated to the `lastMessages` count most recent messages in the thread. When set to `auto`, messages in the middle of the thread + /// will be dropped to fit the context length of the model, `max_prompt_tokens`. + /// + public TruncationObject(TruncationStrategy type) + { + Type = type; + } + + /// Initializes a new instance of . + /// + /// The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will + /// be truncated to the `lastMessages` count most recent messages in the thread. When set to `auto`, messages in the middle of the thread + /// will be dropped to fit the context length of the model, `max_prompt_tokens`. + /// + /// The number of most recent messages from the thread when constructing the context for the run. + /// Keeps track of any properties unknown to the library. + internal TruncationObject(TruncationStrategy type, int? lastMessages, IDictionary serializedAdditionalRawData) + { + Type = type; + LastMessages = lastMessages; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal TruncationObject() + { + } + + /// + /// The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will + /// be truncated to the `lastMessages` count most recent messages in the thread. When set to `auto`, messages in the middle of the thread + /// will be dropped to fit the context length of the model, `max_prompt_tokens`. + /// + public TruncationStrategy Type { get; set; } + /// The number of most recent messages from the thread when constructing the context for the run. + public int? LastMessages { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationStrategy.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationStrategy.cs new file mode 100644 index 000000000000..7e51ad3d3242 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/TruncationStrategy.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Possible truncation strategies for the thread. + public readonly partial struct TruncationStrategy : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public TruncationStrategy(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string LastMessagesValue = "last_messages"; + + /// Default value. Messages in the middle of the thread will be dropped to fit the context length of the model. + public static TruncationStrategy Auto { get; } = new TruncationStrategy(AutoValue); + /// The thread will truncate to the `lastMessages` count of recent messages. + public static TruncationStrategy LastMessages { get; } = new TruncationStrategy(LastMessagesValue); + /// Determines if two values are the same. + public static bool operator ==(TruncationStrategy left, TruncationStrategy right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(TruncationStrategy left, TruncationStrategy right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator TruncationStrategy(string value) => new TruncationStrategy(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is TruncationStrategy other && Equals(other); + /// + public bool Equals(TruncationStrategy other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.Serialization.cs new file mode 100644 index 000000000000..4fb52f3a2e5c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.Serialization.cs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownAssistantsApiResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + AssistantsApiResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAssistantsApiResponseFormat(document.RootElement, options); + } + + internal static UnknownAssistantsApiResponseFormat DeserializeUnknownAssistantsApiResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ApiResponseFormat? type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + type = new ApiResponseFormat(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownAssistantsApiResponseFormat(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + AssistantsApiResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAssistantsApiResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AssistantsApiResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownAssistantsApiResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownAssistantsApiResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.cs new file mode 100644 index 000000000000..8e79946b17e3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownAssistantsApiResponseFormat.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of AssistantsApiResponseFormat. + internal partial class UnknownAssistantsApiResponseFormat : AssistantsApiResponseFormat + { + /// Initializes a new instance of . + /// Must be one of `text`, `json_object` or `json_schema` . + /// Keeps track of any properties unknown to the library. + internal UnknownAssistantsApiResponseFormat(ApiResponseFormat? type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownAssistantsApiResponseFormat() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.Serialization.cs new file mode 100644 index 000000000000..58eb97f774a0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.Serialization.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownMessageDeltaContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + MessageDeltaContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaContent(document.RootElement, options); + } + + internal static UnknownMessageDeltaContent DeserializeUnknownMessageDeltaContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownMessageDeltaContent(index, type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownMessageDeltaContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownMessageDeltaContent(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.cs new file mode 100644 index 000000000000..7b50c79a9122 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaContent.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of MessageDeltaContent. + internal partial class UnknownMessageDeltaContent : MessageDeltaContent + { + /// Initializes a new instance of . + /// The index of the content part of the message. + /// The type of content for this content part. + /// Keeps track of any properties unknown to the library. + internal UnknownMessageDeltaContent(int index, string type, IDictionary serializedAdditionalRawData) : base(index, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownMessageDeltaContent() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.Serialization.cs new file mode 100644 index 000000000000..a3520c9dcea1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.Serialization.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownMessageDeltaTextAnnotation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + MessageDeltaTextAnnotation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + + internal static UnknownMessageDeltaTextAnnotation DeserializeUnknownMessageDeltaTextAnnotation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownMessageDeltaTextAnnotation(index, type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support writing '{options.Format}' format."); + } + } + + MessageDeltaTextAnnotation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMessageDeltaTextAnnotation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MessageDeltaTextAnnotation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownMessageDeltaTextAnnotation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownMessageDeltaTextAnnotation(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.cs new file mode 100644 index 000000000000..3a65e8f866b4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageDeltaTextAnnotation.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of MessageDeltaTextAnnotation. + internal partial class UnknownMessageDeltaTextAnnotation : MessageDeltaTextAnnotation + { + /// Initializes a new instance of . + /// The index of the annotation within a text content part. + /// The type of the text content annotation. + /// Keeps track of any properties unknown to the library. + internal UnknownMessageDeltaTextAnnotation(int index, string type, IDictionary serializedAdditionalRawData) : base(index, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownMessageDeltaTextAnnotation() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs index 1a27fc0aab34..8492c2f302f8 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.Serialization.cs @@ -59,8 +59,6 @@ internal static UnknownMessageTextAnnotation DeserializeUnknownMessageTextAnnota } string type = "Unknown"; string text = default; - int startIndex = default; - int endIndex = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -75,23 +73,13 @@ internal static UnknownMessageTextAnnotation DeserializeUnknownMessageTextAnnota text = property.Value.GetString(); continue; } - if (property.NameEquals("start_index"u8)) - { - startIndex = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("end_index"u8)) - { - endIndex = property.Value.GetInt32(); - continue; - } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new UnknownMessageTextAnnotation(type, text, startIndex, endIndex, serializedAdditionalRawData); + return new UnknownMessageTextAnnotation(type, text, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs index 707b99138307..8df46b4ee1f3 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownMessageTextAnnotation.cs @@ -16,10 +16,8 @@ internal partial class UnknownMessageTextAnnotation : MessageTextAnnotation /// Initializes a new instance of . /// The object type. /// The textual content associated with this text annotation item. - /// The first text index associated with this text annotation. - /// The last text index associated with this text annotation. /// Keeps track of any properties unknown to the library. - internal UnknownMessageTextAnnotation(string type, string text, int startIndex, int endIndex, IDictionary serializedAdditionalRawData) : base(type, text, startIndex, endIndex, serializedAdditionalRawData) + internal UnknownMessageTextAnnotation(string type, string text, IDictionary serializedAdditionalRawData) : base(type, text, serializedAdditionalRawData) { } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.Serialization.cs new file mode 100644 index 000000000000..3ce8d7b7753c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.Serialization.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownRunStepDeltaCodeInterpreterOutput : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + RunStepDeltaCodeInterpreterOutput IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + + internal static UnknownRunStepDeltaCodeInterpreterOutput DeserializeUnknownRunStepDeltaCodeInterpreterOutput(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownRunStepDeltaCodeInterpreterOutput(index, type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaCodeInterpreterOutput IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaCodeInterpreterOutput(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaCodeInterpreterOutput)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownRunStepDeltaCodeInterpreterOutput FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownRunStepDeltaCodeInterpreterOutput(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.cs new file mode 100644 index 000000000000..cda7227367bc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaCodeInterpreterOutput.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of RunStepDeltaCodeInterpreterOutput. + internal partial class UnknownRunStepDeltaCodeInterpreterOutput : RunStepDeltaCodeInterpreterOutput + { + /// Initializes a new instance of . + /// The index of the output in the streaming run step tool call's Code Interpreter outputs array. + /// The type of the streaming run step tool call's Code Interpreter output. + /// Keeps track of any properties unknown to the library. + internal UnknownRunStepDeltaCodeInterpreterOutput(int index, string type, IDictionary serializedAdditionalRawData) : base(index, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownRunStepDeltaCodeInterpreterOutput() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.Serialization.cs new file mode 100644 index 000000000000..ef29b0d92f80 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownRunStepDeltaDetail : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + RunStepDeltaDetail IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaDetail(document.RootElement, options); + } + + internal static UnknownRunStepDeltaDetail DeserializeUnknownRunStepDeltaDetail(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownRunStepDeltaDetail(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaDetail IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaDetail(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaDetail)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownRunStepDeltaDetail FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownRunStepDeltaDetail(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.cs new file mode 100644 index 000000000000..bf9efec7d936 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaDetail.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of RunStepDeltaDetail. + internal partial class UnknownRunStepDeltaDetail : RunStepDeltaDetail + { + /// Initializes a new instance of . + /// The object type for the run step detail object. + /// Keeps track of any properties unknown to the library. + internal UnknownRunStepDeltaDetail(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownRunStepDeltaDetail() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.Serialization.cs new file mode 100644 index 000000000000..2841df37028f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownRunStepDeltaToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + RunStepDeltaToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + + internal static UnknownRunStepDeltaToolCall DeserializeUnknownRunStepDeltaToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int index = default; + string id = default; + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownRunStepDeltaToolCall(index, id, type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support writing '{options.Format}' format."); + } + } + + RunStepDeltaToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeRunStepDeltaToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(RunStepDeltaToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownRunStepDeltaToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownRunStepDeltaToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.cs new file mode 100644 index 000000000000..01e29a7c3518 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownRunStepDeltaToolCall.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of RunStepDeltaToolCall. + internal partial class UnknownRunStepDeltaToolCall : RunStepDeltaToolCall + { + /// Initializes a new instance of . + /// The index of the tool call detail in the run step's tool_calls array. + /// The ID of the tool call, used when submitting outputs to the run. + /// The type of the tool call detail item in a streaming run step's details. + /// Keeps track of any properties unknown to the library. + internal UnknownRunStepDeltaToolCall(int index, string id, string type, IDictionary serializedAdditionalRawData) : base(index, id, type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownRunStepDeltaToolCall() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..fa6625d4e845 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownVectorStoreChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + VectorStoreChunkingStrategyRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + + internal static UnknownVectorStoreChunkingStrategyRequest DeserializeUnknownVectorStoreChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyRequestType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyRequestType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownVectorStoreChunkingStrategyRequest(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownVectorStoreChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownVectorStoreChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.cs new file mode 100644 index 000000000000..287e2c3a3496 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyRequest.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of VectorStoreChunkingStrategyRequest. + internal partial class UnknownVectorStoreChunkingStrategyRequest : VectorStoreChunkingStrategyRequest + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownVectorStoreChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownVectorStoreChunkingStrategyRequest() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..23b989280aa8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + internal partial class UnknownVectorStoreChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + VectorStoreChunkingStrategyResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + + internal static UnknownVectorStoreChunkingStrategyResponse DeserializeUnknownVectorStoreChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyResponseType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyResponseType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownVectorStoreChunkingStrategyResponse(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownVectorStoreChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownVectorStoreChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.cs new file mode 100644 index 000000000000..d81dc4925d3c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UnknownVectorStoreChunkingStrategyResponse.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Unknown version of VectorStoreChunkingStrategyResponse. + internal partial class UnknownVectorStoreChunkingStrategyResponse : VectorStoreChunkingStrategyResponse + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownVectorStoreChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownVectorStoreChunkingStrategyResponse() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs index 921a89074dc7..2806542a5d84 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.Serialization.cs @@ -85,15 +85,53 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } writer.WriteEndArray(); } - if (Optional.IsCollectionDefined(FileIds)) + if (Optional.IsDefined(ToolResources)) { - writer.WritePropertyName("file_ids"u8); - writer.WriteStartArray(); - foreach (var item in FileIds) + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + if (Optional.IsDefined(Temperature)) + { + if (Temperature != null) { - writer.WriteStringValue(item); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + else + { + writer.WriteNull("temperature"); + } + } + if (Optional.IsDefined(TopP)) + { + if (TopP != null) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(TopP.Value); + } + else + { + writer.WriteNull("top_p"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + if (ResponseFormat != null) + { + writer.WritePropertyName("response_format"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ResponseFormat); +#else + using (JsonDocument document = JsonDocument.Parse(ResponseFormat, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("response_format"); } - writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Metadata)) { @@ -155,7 +193,10 @@ internal static UpdateAssistantOptions DeserializeUpdateAssistantOptions(JsonEle string description = default; string instructions = default; IList tools = default; - IList fileIds = default; + UpdateToolResourcesOptions toolResources = default; + float? temperature = default; + float? topP = default; + BinaryData responseFormat = default; IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); @@ -210,18 +251,43 @@ internal static UpdateAssistantOptions DeserializeUpdateAssistantOptions(JsonEle tools = array; continue; } - if (property.NameEquals("file_ids"u8)) + if (property.NameEquals("tool_resources"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - List array = new List(); - foreach (var item in property.Value.EnumerateArray()) + toolResources = UpdateToolResourcesOptions.DeserializeUpdateToolResourcesOptions(property.Value, options); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) { - array.Add(item.GetString()); + temperature = null; + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topP = null; + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + responseFormat = null; + continue; } - fileIds = array; + responseFormat = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("metadata"u8)) @@ -250,7 +316,10 @@ internal static UpdateAssistantOptions DeserializeUpdateAssistantOptions(JsonEle description, instructions, tools ?? new ChangeTrackingList(), - fileIds ?? new ChangeTrackingList(), + toolResources, + temperature, + topP, + responseFormat, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs index 85770c825c21..b3b50cb3bb79 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantOptions.cs @@ -49,7 +49,6 @@ public partial class UpdateAssistantOptions public UpdateAssistantOptions() { Tools = new ChangeTrackingList(); - FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } @@ -61,19 +60,36 @@ public UpdateAssistantOptions() /// /// The modified collection of tools to enable for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// - /// The modified list of previously uploaded fileIDs to attach to the assistant. + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, + /// the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + /// The response format of the tool calls used by this assistant. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal UpdateAssistantOptions(string model, string name, string description, string instructions, IList tools, IList fileIds, IDictionary metadata, IDictionary serializedAdditionalRawData) + internal UpdateAssistantOptions(string model, string name, string description, string instructions, IList tools, UpdateToolResourcesOptions toolResources, float? temperature, float? topP, BinaryData responseFormat, IDictionary metadata, IDictionary serializedAdditionalRawData) { Model = model; Name = name; Description = description; Instructions = instructions; Tools = tools; - FileIds = fileIds; + ToolResources = toolResources; + Temperature = temperature; + TopP = topP; + ResponseFormat = responseFormat; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -89,11 +105,71 @@ internal UpdateAssistantOptions(string model, string name, string description, s /// /// The modified collection of tools to enable for the assistant. /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. - /// The available derived classes include , and . + /// The available derived classes include , and . /// public IList Tools { get; } - /// The modified list of previously uploaded fileIDs to attach to the assistant. - public IList FileIds { get; } + /// + /// A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, + /// the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. + /// + public UpdateToolResourcesOptions ToolResources { get; set; } + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, + /// while lower values like 0.2 will make it more focused and deterministic. + /// + public float? Temperature { get; set; } + /// + /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. + /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. + /// + /// We generally recommend altering this or temperature but not both. + /// + public float? TopP { get; set; } + /// + /// The response format of the tool calls used by this assistant. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ResponseFormat { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. public IDictionary Metadata { get; set; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.Serialization.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.Serialization.cs index 1469ef70a4f8..9d5f8b5e50f7 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class UpdateThreadRequest : IUtf8JsonSerializable, IJsonModel + public partial class UpdateAssistantThreadOptions : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,12 +28,24 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(UpdateThreadRequest)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support writing '{format}' format."); } + if (Optional.IsDefined(ToolResources)) + { + if (ToolResources != null) + { + writer.WritePropertyName("tool_resources"u8); + writer.WriteObjectValue(ToolResources, options); + } + else + { + writer.WriteNull("tool_resources"); + } + } if (Optional.IsCollectionDefined(Metadata)) { if (Metadata != null) @@ -69,19 +81,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - UpdateThreadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + UpdateAssistantThreadOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(UpdateThreadRequest)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeUpdateThreadRequest(document.RootElement, options); + return DeserializeUpdateAssistantThreadOptions(document.RootElement, options); } - internal static UpdateThreadRequest DeserializeUpdateThreadRequest(JsonElement element, ModelReaderWriterOptions options = null) + internal static UpdateAssistantThreadOptions DeserializeUpdateAssistantThreadOptions(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -89,11 +101,22 @@ internal static UpdateThreadRequest DeserializeUpdateThreadRequest(JsonElement e { return null; } - IReadOnlyDictionary metadata = default; + UpdateToolResourcesOptions toolResources = default; + IDictionary metadata = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { + if (property.NameEquals("tool_resources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + toolResources = null; + continue; + } + toolResources = UpdateToolResourcesOptions.DeserializeUpdateToolResourcesOptions(property.Value, options); + continue; + } if (property.NameEquals("metadata"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) @@ -114,46 +137,46 @@ internal static UpdateThreadRequest DeserializeUpdateThreadRequest(JsonElement e } } serializedAdditionalRawData = rawDataDictionary; - return new UpdateThreadRequest(metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + return new UpdateAssistantThreadOptions(toolResources, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(UpdateThreadRequest)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support writing '{options.Format}' format."); } } - UpdateThreadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + UpdateAssistantThreadOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeUpdateThreadRequest(document.RootElement, options); + return DeserializeUpdateAssistantThreadOptions(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(UpdateThreadRequest)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(UpdateAssistantThreadOptions)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static UpdateThreadRequest FromResponse(Response response) + internal static UpdateAssistantThreadOptions FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeUpdateThreadRequest(document.RootElement); + return DeserializeUpdateAssistantThreadOptions(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.cs similarity index 53% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.cs index b58f5b245234..6b7141de049b 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateMessageRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateAssistantThreadOptions.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// The CreateMessageRequest. - internal partial class CreateMessageRequest + /// The details used to update an existing assistant thread. + public partial class UpdateAssistantThreadOptions { /// /// Keeps track of any properties unknown to the library. @@ -45,47 +45,34 @@ internal partial class CreateMessageRequest /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The role to associate with the new message. - /// The textual content for the new message. - /// is null. - internal CreateMessageRequest(MessageRole role, string content) + /// Initializes a new instance of . + public UpdateAssistantThreadOptions() { - Argument.AssertNotNull(content, nameof(content)); - - Role = role; - Content = content; - FileIds = new ChangeTrackingList(); Metadata = new ChangeTrackingDictionary(); } - /// Initializes a new instance of . - /// The role to associate with the new message. - /// The textual content for the new message. - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. + /// Initializes a new instance of . + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs + /// /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal CreateMessageRequest(MessageRole role, string content, IReadOnlyList fileIds, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal UpdateAssistantThreadOptions(UpdateToolResourcesOptions toolResources, IDictionary metadata, IDictionary serializedAdditionalRawData) { - Role = role; - Content = content; - FileIds = fileIds; + ToolResources = toolResources; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal CreateMessageRequest() - { - } - - /// The role to associate with the new message. - public MessageRole Role { get; } - /// The textual content for the new message. - public string Content { get; } - /// A list of up to 10 file IDs to associate with the message, as used by tools like 'code_interpreter' or 'retrieval' that can read files. - public IReadOnlyList FileIds { get; } + /// + /// A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the + /// type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires + /// a list of vector store IDs + /// + public UpdateToolResourcesOptions ToolResources { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - public IReadOnlyDictionary Metadata { get; } + public IDictionary Metadata { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.Serialization.cs new file mode 100644 index 000000000000..d88457c6b5a3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class UpdateCodeInterpreterToolResourceOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UpdateCodeInterpreterToolResourceOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(FileIds)) + { + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + UpdateCodeInterpreterToolResourceOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UpdateCodeInterpreterToolResourceOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpdateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + + internal static UpdateCodeInterpreterToolResourceOptions DeserializeUpdateCodeInterpreterToolResourceOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList fileIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UpdateCodeInterpreterToolResourceOptions(fileIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(UpdateCodeInterpreterToolResourceOptions)} does not support writing '{options.Format}' format."); + } + } + + UpdateCodeInterpreterToolResourceOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpdateCodeInterpreterToolResourceOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UpdateCodeInterpreterToolResourceOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UpdateCodeInterpreterToolResourceOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpdateCodeInterpreterToolResourceOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.cs new file mode 100644 index 000000000000..8c09267cd78d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateCodeInterpreterToolResourceOptions.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Request object to update `code_interpreted` tool resources. + public partial class UpdateCodeInterpreterToolResourceOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public UpdateCodeInterpreterToolResourceOptions() + { + FileIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A list of file IDs to override the current list of the assistant. + /// Keeps track of any properties unknown to the library. + internal UpdateCodeInterpreterToolResourceOptions(IList fileIds, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of file IDs to override the current list of the assistant. + public IList FileIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.Serialization.cs new file mode 100644 index 000000000000..224226046340 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.Serialization.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class UpdateFileSearchToolResourceOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UpdateFileSearchToolResourceOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(VectorStoreIds)) + { + writer.WritePropertyName("vector_store_ids"u8); + writer.WriteStartArray(); + foreach (var item in VectorStoreIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + UpdateFileSearchToolResourceOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UpdateFileSearchToolResourceOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpdateFileSearchToolResourceOptions(document.RootElement, options); + } + + internal static UpdateFileSearchToolResourceOptions DeserializeUpdateFileSearchToolResourceOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList vectorStoreIds = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("vector_store_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorStoreIds = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UpdateFileSearchToolResourceOptions(vectorStoreIds ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(UpdateFileSearchToolResourceOptions)} does not support writing '{options.Format}' format."); + } + } + + UpdateFileSearchToolResourceOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpdateFileSearchToolResourceOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UpdateFileSearchToolResourceOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UpdateFileSearchToolResourceOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpdateFileSearchToolResourceOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.cs new file mode 100644 index 000000000000..8742c5cd1b07 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateFileSearchToolResourceOptions.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Request object to update `file_search` tool resources. + public partial class UpdateFileSearchToolResourceOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public UpdateFileSearchToolResourceOptions() + { + VectorStoreIds = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A list of vector store IDs to override the current list of the assistant. + /// Keeps track of any properties unknown to the library. + internal UpdateFileSearchToolResourceOptions(IList vectorStoreIds, IDictionary serializedAdditionalRawData) + { + VectorStoreIds = vectorStoreIds; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of vector store IDs to override the current list of the assistant. + public IList VectorStoreIds { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.Serialization.cs new file mode 100644 index 000000000000..beeca740951f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.Serialization.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class UpdateToolResourcesOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UpdateToolResourcesOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(CodeInterpreter)) + { + writer.WritePropertyName("code_interpreter"u8); + writer.WriteObjectValue(CodeInterpreter, options); + } + if (Optional.IsDefined(FileSearch)) + { + writer.WritePropertyName("file_search"u8); + writer.WriteObjectValue(FileSearch, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + UpdateToolResourcesOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UpdateToolResourcesOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpdateToolResourcesOptions(document.RootElement, options); + } + + internal static UpdateToolResourcesOptions DeserializeUpdateToolResourcesOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + UpdateCodeInterpreterToolResourceOptions codeInterpreter = default; + UpdateFileSearchToolResourceOptions fileSearch = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code_interpreter"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + codeInterpreter = UpdateCodeInterpreterToolResourceOptions.DeserializeUpdateCodeInterpreterToolResourceOptions(property.Value, options); + continue; + } + if (property.NameEquals("file_search"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fileSearch = UpdateFileSearchToolResourceOptions.DeserializeUpdateFileSearchToolResourceOptions(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UpdateToolResourcesOptions(codeInterpreter, fileSearch, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(UpdateToolResourcesOptions)} does not support writing '{options.Format}' format."); + } + } + + UpdateToolResourcesOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpdateToolResourcesOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UpdateToolResourcesOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UpdateToolResourcesOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpdateToolResourcesOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.cs new file mode 100644 index 000000000000..919e93c57f1f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateToolResourcesOptions.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// Request object. A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. + /// For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of + /// vector store IDs. + /// + public partial class UpdateToolResourcesOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public UpdateToolResourcesOptions() + { + } + + /// Initializes a new instance of . + /// + /// Overrides the list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + /// Overrides the vector store attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + /// Keeps track of any properties unknown to the library. + internal UpdateToolResourcesOptions(UpdateCodeInterpreterToolResourceOptions codeInterpreter, UpdateFileSearchToolResourceOptions fileSearch, IDictionary serializedAdditionalRawData) + { + CodeInterpreter = codeInterpreter; + FileSearch = fileSearch; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// Overrides the list of file IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files + /// associated with the tool. + /// + public UpdateCodeInterpreterToolResourceOptions CodeInterpreter { get; set; } + /// Overrides the vector store attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + public UpdateFileSearchToolResourceOptions FileSearch { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UploadFileRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UploadFileRequest.cs index b5e45145bf9a..5df3f9f91823 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UploadFileRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UploadFileRequest.cs @@ -50,7 +50,7 @@ internal partial class UploadFileRequest /// The file data (not filename) to upload. /// The intended purpose of the file. /// is null. - internal UploadFileRequest(Stream data, OpenAIFilePurpose purpose) + public UploadFileRequest(Stream data, OpenAIFilePurpose purpose) { Argument.AssertNotNull(data, nameof(data)); @@ -81,6 +81,6 @@ internal UploadFileRequest() /// The intended purpose of the file. public OpenAIFilePurpose Purpose { get; } /// A filename to associate with the uploaded data. - public string Filename { get; } + public string Filename { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.Serialization.cs new file mode 100644 index 000000000000..3ec00f4ffec9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.Serialization.cs @@ -0,0 +1,291 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStore : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStore)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("usage_bytes"u8); + writer.WriteNumberValue(UsageBytes); + writer.WritePropertyName("file_counts"u8); + writer.WriteObjectValue(FileCounts, options); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (Optional.IsDefined(ExpiresAfter)) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpiresAfter, options); + } + if (Optional.IsDefined(ExpiresAt)) + { + if (ExpiresAt != null) + { + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt.Value, "U"); + } + else + { + writer.WriteNull("expires_at"); + } + } + if (LastActiveAt != null) + { + writer.WritePropertyName("last_active_at"u8); + writer.WriteNumberValue(LastActiveAt.Value, "U"); + } + else + { + writer.WriteNull("last_active_at"); + } + if (Metadata != null && Optional.IsCollectionDefined(Metadata)) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStore IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStore)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStore(document.RootElement, options); + } + + internal static VectorStore DeserializeVectorStore(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + VectorStoreObject @object = default; + DateTimeOffset createdAt = default; + string name = default; + int usageBytes = default; + VectorStoreFileCount fileCounts = default; + VectorStoreStatus status = default; + VectorStoreExpirationPolicy expiresAfter = default; + DateTimeOffset? expiresAt = default; + DateTimeOffset? lastActiveAt = default; + IReadOnlyDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("usage_bytes"u8)) + { + usageBytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("file_counts"u8)) + { + fileCounts = VectorStoreFileCount.DeserializeVectorStoreFileCount(property.Value, options); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new VectorStoreStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("expires_after"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + expiresAt = null; + continue; + } + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("last_active_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + lastActiveAt = null; + continue; + } + lastActiveAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + metadata = new ChangeTrackingDictionary(); + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStore( + id, + @object, + createdAt, + name, + usageBytes, + fileCounts, + status, + expiresAfter, + expiresAt, + lastActiveAt, + metadata, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStore)} does not support writing '{options.Format}' format."); + } + } + + VectorStore IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStore(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStore)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStore FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStore(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.cs new file mode 100644 index 000000000000..bd3231e10fc6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStore.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A vector store is a collection of processed files can be used by the `file_search` tool. + public partial class VectorStore + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the vector store was created. + /// The name of the vector store. + /// The total number of bytes used by the files in the vector store. + /// Files count grouped by status processed or being processed by this vector store. + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + /// The Unix timestamp (in seconds) for when the vector store was last active. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// , or is null. + internal VectorStore(string id, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCount fileCounts, VectorStoreStatus status, DateTimeOffset? lastActiveAt, IReadOnlyDictionary metadata) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(fileCounts, nameof(fileCounts)); + + Id = id; + CreatedAt = createdAt; + Name = name; + UsageBytes = usageBytes; + FileCounts = fileCounts; + Status = status; + LastActiveAt = lastActiveAt; + Metadata = metadata; + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store`. + /// The Unix timestamp (in seconds) for when the vector store was created. + /// The name of the vector store. + /// The total number of bytes used by the files in the vector store. + /// Files count grouped by status processed or being processed by this vector store. + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + /// Details on when this vector store expires. + /// The Unix timestamp (in seconds) for when the vector store will expire. + /// The Unix timestamp (in seconds) for when the vector store was last active. + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Keeps track of any properties unknown to the library. + internal VectorStore(string id, VectorStoreObject @object, DateTimeOffset createdAt, string name, int usageBytes, VectorStoreFileCount fileCounts, VectorStoreStatus status, VectorStoreExpirationPolicy expiresAfter, DateTimeOffset? expiresAt, DateTimeOffset? lastActiveAt, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + CreatedAt = createdAt; + Name = name; + UsageBytes = usageBytes; + FileCounts = fileCounts; + Status = status; + ExpiresAfter = expiresAfter; + ExpiresAt = expiresAt; + LastActiveAt = lastActiveAt; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStore() + { + } + + /// The identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `vector_store`. + public VectorStoreObject Object { get; } = VectorStoreObject.VectorStore; + + /// The Unix timestamp (in seconds) for when the vector store was created. + public DateTimeOffset CreatedAt { get; } + /// The name of the vector store. + public string Name { get; } + /// The total number of bytes used by the files in the vector store. + public int UsageBytes { get; } + /// Files count grouped by status processed or being processed by this vector store. + public VectorStoreFileCount FileCounts { get; } + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + public VectorStoreStatus Status { get; } + /// Details on when this vector store expires. + public VectorStoreExpirationPolicy ExpiresAfter { get; } + /// The Unix timestamp (in seconds) for when the vector store will expire. + public DateTimeOffset? ExpiresAt { get; } + /// The Unix timestamp (in seconds) for when the vector store was last active. + public DateTimeOffset? LastActiveAt { get; } + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + public IReadOnlyDictionary Metadata { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..b58f5bea42d0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreAutoChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + VectorStoreAutoChunkingStrategyRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreAutoChunkingStrategyRequest(document.RootElement, options); + } + + internal static VectorStoreAutoChunkingStrategyRequest DeserializeVectorStoreAutoChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyRequestType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyRequestType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreAutoChunkingStrategyRequest(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreAutoChunkingStrategyRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreAutoChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreAutoChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreAutoChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.cs new file mode 100644 index 000000000000..54ccde180223 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyRequest.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The default strategy. This strategy currently uses a max_chunk_size_tokens of 800 and chunk_overlap_tokens of 400. + public partial class VectorStoreAutoChunkingStrategyRequest : VectorStoreChunkingStrategyRequest + { + /// Initializes a new instance of . + public VectorStoreAutoChunkingStrategyRequest() + { + Type = VectorStoreChunkingStrategyRequestType.Auto; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreAutoChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..f97bdd43c70b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreAutoChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + VectorStoreAutoChunkingStrategyResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreAutoChunkingStrategyResponse(document.RootElement, options); + } + + internal static VectorStoreAutoChunkingStrategyResponse DeserializeVectorStoreAutoChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreChunkingStrategyResponseType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyResponseType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreAutoChunkingStrategyResponse(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreAutoChunkingStrategyResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreAutoChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreAutoChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreAutoChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreAutoChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.cs new file mode 100644 index 000000000000..17218eca2365 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreAutoChunkingStrategyResponse.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the chunking_strategy concept was introduced in the API. + public partial class VectorStoreAutoChunkingStrategyResponse : VectorStoreChunkingStrategyResponse + { + /// Initializes a new instance of . + internal VectorStoreAutoChunkingStrategyResponse() + { + Type = VectorStoreChunkingStrategyResponseType.Other; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreAutoChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..d8709afaf21c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownVectorStoreChunkingStrategyRequest))] + public partial class VectorStoreChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreChunkingStrategyRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + + internal static VectorStoreChunkingStrategyRequest DeserializeVectorStoreChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "auto": return VectorStoreAutoChunkingStrategyRequest.DeserializeVectorStoreAutoChunkingStrategyRequest(element, options); + case "static": return VectorStoreStaticChunkingStrategyRequest.DeserializeVectorStoreStaticChunkingStrategyRequest(element, options); + } + } + return UnknownVectorStoreChunkingStrategyRequest.DeserializeUnknownVectorStoreChunkingStrategyRequest(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.cs new file mode 100644 index 000000000000..5f64bb63f131 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequest.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// An abstract representation of a vector store chunking strategy configuration. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class VectorStoreChunkingStrategyRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected VectorStoreChunkingStrategyRequest() + { + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type. + internal VectorStoreChunkingStrategyRequestType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequestType.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequestType.cs new file mode 100644 index 000000000000..1b9a9691c970 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyRequestType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Type of chunking strategy. + internal readonly partial struct VectorStoreChunkingStrategyRequestType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreChunkingStrategyRequestType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string StaticValue = "static"; + + /// auto. + public static VectorStoreChunkingStrategyRequestType Auto { get; } = new VectorStoreChunkingStrategyRequestType(AutoValue); + /// static. + public static VectorStoreChunkingStrategyRequestType Static { get; } = new VectorStoreChunkingStrategyRequestType(StaticValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreChunkingStrategyRequestType left, VectorStoreChunkingStrategyRequestType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreChunkingStrategyRequestType left, VectorStoreChunkingStrategyRequestType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreChunkingStrategyRequestType(string value) => new VectorStoreChunkingStrategyRequestType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreChunkingStrategyRequestType other && Equals(other); + /// + public bool Equals(VectorStoreChunkingStrategyRequestType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..c7888938c540 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + [PersistableModelProxy(typeof(UnknownVectorStoreChunkingStrategyResponse))] + public partial class VectorStoreChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreChunkingStrategyResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + + internal static VectorStoreChunkingStrategyResponse DeserializeVectorStoreChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "other": return VectorStoreAutoChunkingStrategyResponse.DeserializeVectorStoreAutoChunkingStrategyResponse(element, options); + case "static": return VectorStoreStaticChunkingStrategyResponse.DeserializeVectorStoreStaticChunkingStrategyResponse(element, options); + } + } + return UnknownVectorStoreChunkingStrategyResponse.DeserializeUnknownVectorStoreChunkingStrategyResponse(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreChunkingStrategyResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.cs new file mode 100644 index 000000000000..a4e4bac4d2a8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponse.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// + /// An abstract representation of a vector store chunking strategy configuration. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class VectorStoreChunkingStrategyResponse + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected VectorStoreChunkingStrategyResponse() + { + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal VectorStoreChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type. + internal VectorStoreChunkingStrategyResponseType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponseType.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponseType.cs new file mode 100644 index 000000000000..8b4d6338955c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreChunkingStrategyResponseType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Type of chunking strategy. + internal readonly partial struct VectorStoreChunkingStrategyResponseType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreChunkingStrategyResponseType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string OtherValue = "other"; + private const string StaticValue = "static"; + + /// other. + public static VectorStoreChunkingStrategyResponseType Other { get; } = new VectorStoreChunkingStrategyResponseType(OtherValue); + /// static. + public static VectorStoreChunkingStrategyResponseType Static { get; } = new VectorStoreChunkingStrategyResponseType(StaticValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreChunkingStrategyResponseType left, VectorStoreChunkingStrategyResponseType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreChunkingStrategyResponseType left, VectorStoreChunkingStrategyResponseType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreChunkingStrategyResponseType(string value) => new VectorStoreChunkingStrategyResponseType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreChunkingStrategyResponseType other && Equals(other); + /// + public bool Equals(VectorStoreChunkingStrategyResponseType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.Serialization.cs similarity index 64% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.Serialization.cs index 99bae8e62025..eb4873d43644 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.Serialization.cs @@ -13,11 +13,11 @@ namespace Azure.AI.OpenAI.Assistants { - internal partial class InternalAssistantFileDeletionStatus : IUtf8JsonSerializable, IJsonModel + public partial class VectorStoreDeletionStatus : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,10 +28,10 @@ void IJsonModel.Write(Utf8JsonWriter writer /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalAssistantFileDeletionStatus)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support writing '{format}' format."); } writer.WritePropertyName("id"u8); @@ -57,19 +57,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - InternalAssistantFileDeletionStatus IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreDeletionStatus IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(InternalAssistantFileDeletionStatus)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAssistantFileDeletionStatus(document.RootElement, options); + return DeserializeVectorStoreDeletionStatus(document.RootElement, options); } - internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistantFileDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreDeletionStatus DeserializeVectorStoreDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,7 +79,7 @@ internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistant } string id = default; bool deleted = default; - InternalAssistantFileDeletionStatusObject @object = default; + VectorStoreDeletionStatusObject @object = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -96,7 +96,7 @@ internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistant } if (property.NameEquals("object"u8)) { - @object = new InternalAssistantFileDeletionStatusObject(property.Value.GetString()); + @object = new VectorStoreDeletionStatusObject(property.Value.GetString()); continue; } if (options.Format != "W") @@ -105,46 +105,46 @@ internal static InternalAssistantFileDeletionStatus DeserializeInternalAssistant } } serializedAdditionalRawData = rawDataDictionary; - return new InternalAssistantFileDeletionStatus(id, deleted, @object, serializedAdditionalRawData); + return new VectorStoreDeletionStatus(id, deleted, @object, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(InternalAssistantFileDeletionStatus)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support writing '{options.Format}' format."); } } - InternalAssistantFileDeletionStatus IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + VectorStoreDeletionStatus IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeInternalAssistantFileDeletionStatus(document.RootElement, options); + return DeserializeVectorStoreDeletionStatus(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(InternalAssistantFileDeletionStatus)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(VectorStoreDeletionStatus)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static InternalAssistantFileDeletionStatus FromResponse(Response response) + internal static VectorStoreDeletionStatus FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeInternalAssistantFileDeletionStatus(document.RootElement); + return DeserializeVectorStoreDeletionStatus(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.cs similarity index 71% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.cs index 1a91eb299ceb..959f2da309e7 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/InternalAssistantFileDeletionStatus.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatus.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// The status of an assistant file deletion operation. - internal partial class InternalAssistantFileDeletionStatus + /// Response object for deleting a vector store. + public partial class VectorStoreDeletionStatus { /// /// Keeps track of any properties unknown to the library. @@ -45,11 +45,11 @@ internal partial class InternalAssistantFileDeletionStatus /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The ID of the resource specified for deletion. /// A value indicating whether deletion was successful. /// is null. - internal InternalAssistantFileDeletionStatus(string id, bool deleted) + internal VectorStoreDeletionStatus(string id, bool deleted) { Argument.AssertNotNull(id, nameof(id)); @@ -57,12 +57,12 @@ internal InternalAssistantFileDeletionStatus(string id, bool deleted) Deleted = deleted; } - /// Initializes a new instance of . + /// Initializes a new instance of . /// The ID of the resource specified for deletion. /// A value indicating whether deletion was successful. - /// The object type, which is always 'assistant.file.deleted'. + /// The object type, which is always 'vector_store.deleted'. /// Keeps track of any properties unknown to the library. - internal InternalAssistantFileDeletionStatus(string id, bool deleted, InternalAssistantFileDeletionStatusObject @object, IDictionary serializedAdditionalRawData) + internal VectorStoreDeletionStatus(string id, bool deleted, VectorStoreDeletionStatusObject @object, IDictionary serializedAdditionalRawData) { Id = id; Deleted = deleted; @@ -70,8 +70,8 @@ internal InternalAssistantFileDeletionStatus(string id, bool deleted, InternalAs _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal InternalAssistantFileDeletionStatus() + /// Initializes a new instance of for deserialization. + internal VectorStoreDeletionStatus() { } @@ -79,7 +79,7 @@ internal InternalAssistantFileDeletionStatus() public string Id { get; } /// A value indicating whether deletion was successful. public bool Deleted { get; } - /// The object type, which is always 'assistant.file.deleted'. - public InternalAssistantFileDeletionStatusObject Object { get; } = InternalAssistantFileDeletionStatusObject.AssistantFileDeleted; + /// The object type, which is always 'vector_store.deleted'. + public VectorStoreDeletionStatusObject Object { get; } = VectorStoreDeletionStatusObject.VectorStoreDeleted; } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatusObject.cs new file mode 100644 index 000000000000..240b13fab2c5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreDeletionStatusObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreDeletionStatus_object. + public readonly partial struct VectorStoreDeletionStatusObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreDeletionStatusObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreDeletedValue = "vector_store.deleted"; + + /// vector_store.deleted. + public static VectorStoreDeletionStatusObject VectorStoreDeleted { get; } = new VectorStoreDeletionStatusObject(VectorStoreDeletedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreDeletionStatusObject left, VectorStoreDeletionStatusObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreDeletionStatusObject left, VectorStoreDeletionStatusObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreDeletionStatusObject(string value) => new VectorStoreDeletionStatusObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreDeletionStatusObject other && Equals(other); + /// + public bool Equals(VectorStoreDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.Serialization.cs similarity index 65% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.Serialization.cs index 15b072f6e4b7..c0be5ad35db4 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessSessionResult.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI.Assistants { - public partial class CreateLivenessSessionResult : IUtf8JsonSerializable, IJsonModel + public partial class VectorStoreExpirationPolicy : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,16 +28,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelR /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(VectorStoreExpirationPolicy)} does not support writing '{format}' format."); } - writer.WritePropertyName("sessionId"u8); - writer.WriteStringValue(SessionId); - writer.WritePropertyName("authToken"u8); - writer.WriteStringValue(AuthToken); + writer.WritePropertyName("anchor"u8); + writer.WriteStringValue(Anchor.ToString()); + writer.WritePropertyName("days"u8); + writer.WriteNumberValue(Days); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -55,19 +55,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - CreateLivenessSessionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + VectorStoreExpirationPolicy IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(VectorStoreExpirationPolicy)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateLivenessSessionResult(document.RootElement, options); + return DeserializeVectorStoreExpirationPolicy(document.RootElement, options); } - internal static CreateLivenessSessionResult DeserializeCreateLivenessSessionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static VectorStoreExpirationPolicy DeserializeVectorStoreExpirationPolicy(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -75,20 +75,20 @@ internal static CreateLivenessSessionResult DeserializeCreateLivenessSessionResu { return null; } - string sessionId = default; - string authToken = default; + VectorStoreExpirationPolicyAnchor anchor = default; + int days = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("sessionId"u8)) + if (property.NameEquals("anchor"u8)) { - sessionId = property.Value.GetString(); + anchor = new VectorStoreExpirationPolicyAnchor(property.Value.GetString()); continue; } - if (property.NameEquals("authToken"u8)) + if (property.NameEquals("days"u8)) { - authToken = property.Value.GetString(); + days = property.Value.GetInt32(); continue; } if (options.Format != "W") @@ -97,46 +97,46 @@ internal static CreateLivenessSessionResult DeserializeCreateLivenessSessionResu } } serializedAdditionalRawData = rawDataDictionary; - return new CreateLivenessSessionResult(sessionId, authToken, serializedAdditionalRawData); + return new VectorStoreExpirationPolicy(anchor, days, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(VectorStoreExpirationPolicy)} does not support writing '{options.Format}' format."); } } - CreateLivenessSessionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + VectorStoreExpirationPolicy IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessSessionResult(document.RootElement, options); + return DeserializeVectorStoreExpirationPolicy(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateLivenessSessionResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(VectorStoreExpirationPolicy)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateLivenessSessionResult FromResponse(Response response) + internal static VectorStoreExpirationPolicy FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessSessionResult(document.RootElement); + return DeserializeVectorStoreExpirationPolicy(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.cs new file mode 100644 index 000000000000..345d82299d9d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicy.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The expiration policy for a vector store. + public partial class VectorStoreExpirationPolicy + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. + /// The anchor timestamp after which the expiration policy applies. + public VectorStoreExpirationPolicy(VectorStoreExpirationPolicyAnchor anchor, int days) + { + Anchor = anchor; + Days = days; + } + + /// Initializes a new instance of . + /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. + /// The anchor timestamp after which the expiration policy applies. + /// Keeps track of any properties unknown to the library. + internal VectorStoreExpirationPolicy(VectorStoreExpirationPolicyAnchor anchor, int days, IDictionary serializedAdditionalRawData) + { + Anchor = anchor; + Days = days; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreExpirationPolicy() + { + } + + /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. + public VectorStoreExpirationPolicyAnchor Anchor { get; set; } + /// The anchor timestamp after which the expiration policy applies. + public int Days { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicyAnchor.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicyAnchor.cs new file mode 100644 index 000000000000..864a769e6b50 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreExpirationPolicyAnchor.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Describes the relationship between the days and the expiration of this vector store. + public readonly partial struct VectorStoreExpirationPolicyAnchor : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreExpirationPolicyAnchor(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string LastActiveAtValue = "last_active_at"; + + /// The expiration policy is based on the last time the vector store was active. + public static VectorStoreExpirationPolicyAnchor LastActiveAt { get; } = new VectorStoreExpirationPolicyAnchor(LastActiveAtValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreExpirationPolicyAnchor left, VectorStoreExpirationPolicyAnchor right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreExpirationPolicyAnchor left, VectorStoreExpirationPolicyAnchor right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreExpirationPolicyAnchor(string value) => new VectorStoreExpirationPolicyAnchor(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreExpirationPolicyAnchor other && Equals(other); + /// + public bool Equals(VectorStoreExpirationPolicyAnchor other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.Serialization.cs new file mode 100644 index 000000000000..a2ce877adbc7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.Serialization.cs @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFile : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFile)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("usage_bytes"u8); + writer.WriteNumberValue(UsageBytes); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("vector_store_id"u8); + writer.WriteStringValue(VectorStoreId); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + if (LastError != null) + { + writer.WritePropertyName("last_error"u8); + writer.WriteObjectValue(LastError, options); + } + else + { + writer.WriteNull("last_error"); + } + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFile)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFile(document.RootElement, options); + } + + internal static VectorStoreFile DeserializeVectorStoreFile(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + VectorStoreFileObject @object = default; + int usageBytes = default; + DateTimeOffset createdAt = default; + string vectorStoreId = default; + VectorStoreFileStatus status = default; + VectorStoreFileError lastError = default; + VectorStoreChunkingStrategyResponse chunkingStrategy = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreFileObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("usage_bytes"u8)) + { + usageBytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("vector_store_id"u8)) + { + vectorStoreId = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new VectorStoreFileStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("last_error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + lastError = null; + continue; + } + lastError = VectorStoreFileError.DeserializeVectorStoreFileError(property.Value, options); + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + chunkingStrategy = VectorStoreChunkingStrategyResponse.DeserializeVectorStoreChunkingStrategyResponse(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFile( + id, + @object, + usageBytes, + createdAt, + vectorStoreId, + status, + lastError, + chunkingStrategy, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreFile)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFile(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFile)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFile FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFile(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.cs new file mode 100644 index 000000000000..d7c12dbf07d8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFile.cs @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Description of a file attached to a vector store. + public partial class VectorStoreFile + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + /// The Unix timestamp (in seconds) for when the vector store file was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + /// The last error associated with this vector store file. Will be `null` if there are no errors. + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// , or is null. + internal VectorStoreFile(string id, int usageBytes, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileStatus status, VectorStoreFileError lastError, VectorStoreChunkingStrategyResponse chunkingStrategy) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(chunkingStrategy, nameof(chunkingStrategy)); + + Id = id; + UsageBytes = usageBytes; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + LastError = lastError; + ChunkingStrategy = chunkingStrategy; + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file`. + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + /// The Unix timestamp (in seconds) for when the vector store file was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + /// The last error associated with this vector store file. Will be `null` if there are no errors. + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// Keeps track of any properties unknown to the library. + internal VectorStoreFile(string id, VectorStoreFileObject @object, int usageBytes, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileStatus status, VectorStoreFileError lastError, VectorStoreChunkingStrategyResponse chunkingStrategy, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + UsageBytes = usageBytes; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + LastError = lastError; + ChunkingStrategy = chunkingStrategy; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFile() + { + } + + /// The identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `vector_store.file`. + public VectorStoreFileObject Object { get; } = VectorStoreFileObject.VectorStoreFile; + + /// + /// The total vector store usage in bytes. Note that this may be different from the original file + /// size. + /// + public int UsageBytes { get; } + /// The Unix timestamp (in seconds) for when the vector store file was created. + public DateTimeOffset CreatedAt { get; } + /// The ID of the vector store that the file is attached to. + public string VectorStoreId { get; } + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + public VectorStoreFileStatus Status { get; } + /// The last error associated with this vector store file. Will be `null` if there are no errors. + public VectorStoreFileError LastError { get; } + /// + /// The strategy used to chunk the file. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyResponse ChunkingStrategy { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.Serialization.cs new file mode 100644 index 000000000000..76745044dfb1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.Serialization.cs @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileBatch : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileBatch)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("vector_store_id"u8); + writer.WriteStringValue(VectorStoreId); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + writer.WritePropertyName("file_counts"u8); + writer.WriteObjectValue(FileCounts, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreFileBatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileBatch)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileBatch(document.RootElement, options); + } + + internal static VectorStoreFileBatch DeserializeVectorStoreFileBatch(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + VectorStoreFileBatchObject @object = default; + DateTimeOffset createdAt = default; + string vectorStoreId = default; + VectorStoreFileBatchStatus status = default; + VectorStoreFileCount fileCounts = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreFileBatchObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("vector_store_id"u8)) + { + vectorStoreId = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new VectorStoreFileBatchStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("file_counts"u8)) + { + fileCounts = VectorStoreFileCount.DeserializeVectorStoreFileCount(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileBatch( + id, + @object, + createdAt, + vectorStoreId, + status, + fileCounts, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreFileBatch)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileBatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileBatch(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileBatch)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileBatch FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileBatch(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.cs new file mode 100644 index 000000000000..898dd2ab2b55 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatch.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A batch of files attached to a vector store. + public partial class VectorStoreFileBatch + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + /// Files count grouped by status processed or being processed by this vector store. + /// , or is null. + internal VectorStoreFileBatch(string id, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileBatchStatus status, VectorStoreFileCount fileCounts) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(vectorStoreId, nameof(vectorStoreId)); + Argument.AssertNotNull(fileCounts, nameof(fileCounts)); + + Id = id; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + FileCounts = fileCounts; + } + + /// Initializes a new instance of . + /// The identifier, which can be referenced in API endpoints. + /// The object type, which is always `vector_store.file_batch`. + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + /// The ID of the vector store that the file is attached to. + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + /// Files count grouped by status processed or being processed by this vector store. + /// Keeps track of any properties unknown to the library. + internal VectorStoreFileBatch(string id, VectorStoreFileBatchObject @object, DateTimeOffset createdAt, string vectorStoreId, VectorStoreFileBatchStatus status, VectorStoreFileCount fileCounts, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + CreatedAt = createdAt; + VectorStoreId = vectorStoreId; + Status = status; + FileCounts = fileCounts; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFileBatch() + { + } + + /// The identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The object type, which is always `vector_store.file_batch`. + public VectorStoreFileBatchObject Object { get; } = VectorStoreFileBatchObject.VectorStoreFilesBatch; + + /// The Unix timestamp (in seconds) for when the vector store files batch was created. + public DateTimeOffset CreatedAt { get; } + /// The ID of the vector store that the file is attached to. + public string VectorStoreId { get; } + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + public VectorStoreFileBatchStatus Status { get; } + /// Files count grouped by status processed or being processed by this vector store. + public VectorStoreFileCount FileCounts { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchObject.cs new file mode 100644 index 000000000000..ff607d482dfa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreFileBatch_object. + public readonly partial struct VectorStoreFileBatchObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileBatchObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreFilesBatchValue = "vector_store.files_batch"; + + /// vector_store.files_batch. + public static VectorStoreFileBatchObject VectorStoreFilesBatch { get; } = new VectorStoreFileBatchObject(VectorStoreFilesBatchValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileBatchObject left, VectorStoreFileBatchObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileBatchObject left, VectorStoreFileBatchObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileBatchObject(string value) => new VectorStoreFileBatchObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileBatchObject other && Equals(other); + /// + public bool Equals(VectorStoreFileBatchObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchStatus.cs new file mode 100644 index 000000000000..79d886ab6ccd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileBatchStatus.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The status of the vector store file batch. + public readonly partial struct VectorStoreFileBatchStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileBatchStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + private const string CancelledValue = "cancelled"; + private const string FailedValue = "failed"; + + /// The vector store is still processing this file batch. + public static VectorStoreFileBatchStatus InProgress { get; } = new VectorStoreFileBatchStatus(InProgressValue); + /// the vector store file batch is ready for use. + public static VectorStoreFileBatchStatus Completed { get; } = new VectorStoreFileBatchStatus(CompletedValue); + /// The vector store file batch was cancelled. + public static VectorStoreFileBatchStatus Cancelled { get; } = new VectorStoreFileBatchStatus(CancelledValue); + /// The vector store file batch failed to process. + public static VectorStoreFileBatchStatus Failed { get; } = new VectorStoreFileBatchStatus(FailedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileBatchStatus left, VectorStoreFileBatchStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileBatchStatus left, VectorStoreFileBatchStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileBatchStatus(string value) => new VectorStoreFileBatchStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileBatchStatus other && Equals(other); + /// + public bool Equals(VectorStoreFileBatchStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.Serialization.cs new file mode 100644 index 000000000000..5aabbfa099b3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.Serialization.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileCount : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileCount)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("in_progress"u8); + writer.WriteNumberValue(InProgress); + writer.WritePropertyName("completed"u8); + writer.WriteNumberValue(Completed); + writer.WritePropertyName("failed"u8); + writer.WriteNumberValue(Failed); + writer.WritePropertyName("cancelled"u8); + writer.WriteNumberValue(Cancelled); + writer.WritePropertyName("total"u8); + writer.WriteNumberValue(Total); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreFileCount IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileCount)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileCount(document.RootElement, options); + } + + internal static VectorStoreFileCount DeserializeVectorStoreFileCount(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int inProgress = default; + int completed = default; + int failed = default; + int cancelled = default; + int total = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("in_progress"u8)) + { + inProgress = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("completed"u8)) + { + completed = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("failed"u8)) + { + failed = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("cancelled"u8)) + { + cancelled = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("total"u8)) + { + total = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileCount( + inProgress, + completed, + failed, + cancelled, + total, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreFileCount)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileCount IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileCount(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileCount)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileCount FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileCount(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.cs new file mode 100644 index 000000000000..a4fe9273bff4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileCount.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Counts of files processed or being processed by this vector store grouped by status. + public partial class VectorStoreFileCount + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The number of files that are currently being processed. + /// The number of files that have been successfully processed. + /// The number of files that have failed to process. + /// The number of files that were cancelled. + /// The total number of files. + internal VectorStoreFileCount(int inProgress, int completed, int failed, int cancelled, int total) + { + InProgress = inProgress; + Completed = completed; + Failed = failed; + Cancelled = cancelled; + Total = total; + } + + /// Initializes a new instance of . + /// The number of files that are currently being processed. + /// The number of files that have been successfully processed. + /// The number of files that have failed to process. + /// The number of files that were cancelled. + /// The total number of files. + /// Keeps track of any properties unknown to the library. + internal VectorStoreFileCount(int inProgress, int completed, int failed, int cancelled, int total, IDictionary serializedAdditionalRawData) + { + InProgress = inProgress; + Completed = completed; + Failed = failed; + Cancelled = cancelled; + Total = total; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFileCount() + { + } + + /// The number of files that are currently being processed. + public int InProgress { get; } + /// The number of files that have been successfully processed. + public int Completed { get; } + /// The number of files that have failed to process. + public int Failed { get; } + /// The number of files that were cancelled. + public int Cancelled { get; } + /// The total number of files. + public int Total { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.Serialization.cs new file mode 100644 index 000000000000..ec1a3c42e1dc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileDeletionStatus : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileDeletionStatus)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("deleted"u8); + writer.WriteBooleanValue(Deleted); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreFileDeletionStatus IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileDeletionStatus)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileDeletionStatus(document.RootElement, options); + } + + internal static VectorStoreFileDeletionStatus DeserializeVectorStoreFileDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + bool deleted = default; + VectorStoreFileDeletionStatusObject @object = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("deleted"u8)) + { + deleted = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new VectorStoreFileDeletionStatusObject(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileDeletionStatus(id, deleted, @object, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreFileDeletionStatus)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileDeletionStatus IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileDeletionStatus(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileDeletionStatus)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileDeletionStatus FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileDeletionStatus(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.cs new file mode 100644 index 000000000000..009e5942a8ac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatus.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Response object for deleting a vector store file relationship. + public partial class VectorStoreFileDeletionStatus + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// is null. + internal VectorStoreFileDeletionStatus(string id, bool deleted) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + Deleted = deleted; + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'vector_store.deleted'. + /// Keeps track of any properties unknown to the library. + internal VectorStoreFileDeletionStatus(string id, bool deleted, VectorStoreFileDeletionStatusObject @object, IDictionary serializedAdditionalRawData) + { + Id = id; + Deleted = deleted; + Object = @object; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFileDeletionStatus() + { + } + + /// The ID of the resource specified for deletion. + public string Id { get; } + /// A value indicating whether deletion was successful. + public bool Deleted { get; } + /// The object type, which is always 'vector_store.deleted'. + public VectorStoreFileDeletionStatusObject Object { get; } = VectorStoreFileDeletionStatusObject.VectorStoreFileDeleted; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatusObject.cs new file mode 100644 index 000000000000..ebd2a6f4d22f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileDeletionStatusObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreFileDeletionStatus_object. + public readonly partial struct VectorStoreFileDeletionStatusObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileDeletionStatusObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreFileDeletedValue = "vector_store.file.deleted"; + + /// vector_store.file.deleted. + public static VectorStoreFileDeletionStatusObject VectorStoreFileDeleted { get; } = new VectorStoreFileDeletionStatusObject(VectorStoreFileDeletedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileDeletionStatusObject left, VectorStoreFileDeletionStatusObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileDeletionStatusObject left, VectorStoreFileDeletionStatusObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileDeletionStatusObject(string value) => new VectorStoreFileDeletionStatusObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileDeletionStatusObject other && Equals(other); + /// + public bool Equals(VectorStoreFileDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.Serialization.cs new file mode 100644 index 000000000000..daf2ec2550de --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreFileError : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileError)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code.ToString()); + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreFileError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreFileError)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreFileError(document.RootElement, options); + } + + internal static VectorStoreFileError DeserializeVectorStoreFileError(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreFileErrorCode code = default; + string message = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code"u8)) + { + code = new VectorStoreFileErrorCode(property.Value.GetString()); + continue; + } + if (property.NameEquals("message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreFileError(code, message, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreFileError)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreFileError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileError(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreFileError)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreFileError FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreFileError(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.cs new file mode 100644 index 000000000000..5c96944e5f8e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileError.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Details on the error that may have ocurred while processing a file for this vector store. + public partial class VectorStoreFileError + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// One of `server_error` or `rate_limit_exceeded`. + /// A human-readable description of the error. + /// is null. + internal VectorStoreFileError(VectorStoreFileErrorCode code, string message) + { + Argument.AssertNotNull(message, nameof(message)); + + Code = code; + Message = message; + } + + /// Initializes a new instance of . + /// One of `server_error` or `rate_limit_exceeded`. + /// A human-readable description of the error. + /// Keeps track of any properties unknown to the library. + internal VectorStoreFileError(VectorStoreFileErrorCode code, string message, IDictionary serializedAdditionalRawData) + { + Code = code; + Message = message; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreFileError() + { + } + + /// One of `server_error` or `rate_limit_exceeded`. + public VectorStoreFileErrorCode Code { get; } + /// A human-readable description of the error. + public string Message { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileErrorCode.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileErrorCode.cs new file mode 100644 index 000000000000..62944f11529e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileErrorCode.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Error code variants for vector store file processing. + public readonly partial struct VectorStoreFileErrorCode : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileErrorCode(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ServerErrorValue = "server_error"; + private const string UnsupportedFileValue = "unsupported_file"; + private const string InvalidFileValue = "invalid_file"; + + /// The server encountered an error. + public static VectorStoreFileErrorCode ServerError { get; } = new VectorStoreFileErrorCode(ServerErrorValue); + /// The file format is not supported. + public static VectorStoreFileErrorCode UnsupportedFile { get; } = new VectorStoreFileErrorCode(UnsupportedFileValue); + /// The file is invalid. + public static VectorStoreFileErrorCode InvalidFile { get; } = new VectorStoreFileErrorCode(InvalidFileValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileErrorCode left, VectorStoreFileErrorCode right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileErrorCode left, VectorStoreFileErrorCode right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileErrorCode(string value) => new VectorStoreFileErrorCode(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileErrorCode other && Equals(other); + /// + public bool Equals(VectorStoreFileErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileObject.cs new file mode 100644 index 000000000000..f4d205e40ce2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStoreFile_object. + public readonly partial struct VectorStoreFileObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreFileValue = "vector_store.file"; + + /// vector_store.file. + public static VectorStoreFileObject VectorStoreFile { get; } = new VectorStoreFileObject(VectorStoreFileValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileObject left, VectorStoreFileObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileObject left, VectorStoreFileObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileObject(string value) => new VectorStoreFileObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileObject other && Equals(other); + /// + public bool Equals(VectorStoreFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatus.cs new file mode 100644 index 000000000000..62c5dc3711e8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatus.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Vector store file status. + public readonly partial struct VectorStoreFileStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + private const string FailedValue = "failed"; + private const string CancelledValue = "cancelled"; + + /// The file is currently being processed. + public static VectorStoreFileStatus InProgress { get; } = new VectorStoreFileStatus(InProgressValue); + /// The file has been successfully processed. + public static VectorStoreFileStatus Completed { get; } = new VectorStoreFileStatus(CompletedValue); + /// The file has failed to process. + public static VectorStoreFileStatus Failed { get; } = new VectorStoreFileStatus(FailedValue); + /// The file was cancelled. + public static VectorStoreFileStatus Cancelled { get; } = new VectorStoreFileStatus(CancelledValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileStatus left, VectorStoreFileStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileStatus left, VectorStoreFileStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileStatus(string value) => new VectorStoreFileStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileStatus other && Equals(other); + /// + public bool Equals(VectorStoreFileStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatusFilter.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatusFilter.cs new file mode 100644 index 000000000000..cd796f8cae2a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreFileStatusFilter.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Query parameter filter for vector store file retrieval endpoint. + public readonly partial struct VectorStoreFileStatusFilter : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreFileStatusFilter(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + private const string FailedValue = "failed"; + private const string CancelledValue = "cancelled"; + + /// Retrieve only files that are currently being processed. + public static VectorStoreFileStatusFilter InProgress { get; } = new VectorStoreFileStatusFilter(InProgressValue); + /// Retrieve only files that have been successfully processed. + public static VectorStoreFileStatusFilter Completed { get; } = new VectorStoreFileStatusFilter(CompletedValue); + /// Retrieve only files that have failed to process. + public static VectorStoreFileStatusFilter Failed { get; } = new VectorStoreFileStatusFilter(FailedValue); + /// Retrieve only files that were cancelled. + public static VectorStoreFileStatusFilter Cancelled { get; } = new VectorStoreFileStatusFilter(CancelledValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreFileStatusFilter left, VectorStoreFileStatusFilter right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreFileStatusFilter left, VectorStoreFileStatusFilter right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreFileStatusFilter(string value) => new VectorStoreFileStatusFilter(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreFileStatusFilter other && Equals(other); + /// + public bool Equals(VectorStoreFileStatusFilter other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreObject.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreObject.cs new file mode 100644 index 000000000000..abbc8b915139 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// The VectorStore_object. + public readonly partial struct VectorStoreObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string VectorStoreValue = "vector_store"; + + /// vector_store. + public static VectorStoreObject VectorStore { get; } = new VectorStoreObject(VectorStoreValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreObject left, VectorStoreObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreObject left, VectorStoreObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreObject(string value) => new VectorStoreObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreObject other && Equals(other); + /// + public bool Equals(VectorStoreObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.Serialization.cs new file mode 100644 index 000000000000..31572f50309a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.Serialization.cs @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(FileIds)) + { + writer.WritePropertyName("file_ids"u8); + writer.WriteStartArray(); + foreach (var item in FileIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsDefined(ExpiresAfter)) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpiresAfter, options); + } + if (Optional.IsDefined(ChunkingStrategy)) + { + writer.WritePropertyName("chunking_strategy"u8); + writer.WriteObjectValue(ChunkingStrategy, options); + } + if (Optional.IsCollectionDefined(Metadata)) + { + if (Metadata != null) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreOptions(document.RootElement, options); + } + + internal static VectorStoreOptions DeserializeVectorStoreOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList fileIds = default; + string name = default; + VectorStoreExpirationPolicy expiresAfter = default; + VectorStoreChunkingStrategyRequest chunkingStrategy = default; + IDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file_ids"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + fileIds = array; + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("expires_after"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + continue; + } + if (property.NameEquals("chunking_strategy"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + chunkingStrategy = VectorStoreChunkingStrategyRequest.DeserializeVectorStoreChunkingStrategyRequest(property.Value, options); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreOptions( + fileIds ?? new ChangeTrackingList(), + name, + expiresAfter, + chunkingStrategy, + metadata ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreOptions)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.cs new file mode 100644 index 000000000000..2aa8bd2f3858 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreOptions.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Request object for creating a vector store. + public partial class VectorStoreOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public VectorStoreOptions() + { + FileIds = new ChangeTrackingList(); + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// A list of file IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// The name of the vector store. + /// Details on when this vector store expires. + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. Only applicable if file_ids is non-empty. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + /// Keeps track of any properties unknown to the library. + internal VectorStoreOptions(IList fileIds, string name, VectorStoreExpirationPolicy expiresAfter, VectorStoreChunkingStrategyRequest chunkingStrategy, IDictionary metadata, IDictionary serializedAdditionalRawData) + { + FileIds = fileIds; + Name = name; + ExpiresAfter = expiresAfter; + ChunkingStrategy = chunkingStrategy; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A list of file IDs that the vector store should use. Useful for tools like `file_search` that can access files. + public IList FileIds { get; } + /// The name of the vector store. + public string Name { get; set; } + /// Details on when this vector store expires. + public VectorStoreExpirationPolicy ExpiresAfter { get; set; } + /// + /// The chunking strategy used to chunk the file(s). If not set, will use the auto strategy. Only applicable if file_ids is non-empty. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public VectorStoreChunkingStrategyRequest ChunkingStrategy { get; set; } + /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. + public IDictionary Metadata { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.Serialization.cs new file mode 100644 index 000000000000..21b248f546ff --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreStaticChunkingStrategyOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("max_chunk_size_tokens"u8); + writer.WriteNumberValue(MaxChunkSizeTokens); + writer.WritePropertyName("chunk_overlap_tokens"u8); + writer.WriteNumberValue(ChunkOverlapTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreStaticChunkingStrategyOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreStaticChunkingStrategyOptions(document.RootElement, options); + } + + internal static VectorStoreStaticChunkingStrategyOptions DeserializeVectorStoreStaticChunkingStrategyOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int maxChunkSizeTokens = default; + int chunkOverlapTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("max_chunk_size_tokens"u8)) + { + maxChunkSizeTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("chunk_overlap_tokens"u8)) + { + chunkOverlapTokens = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreStaticChunkingStrategyOptions(maxChunkSizeTokens, chunkOverlapTokens, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyOptions)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreStaticChunkingStrategyOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreStaticChunkingStrategyOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreStaticChunkingStrategyOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreStaticChunkingStrategyOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.cs new file mode 100644 index 000000000000..38db6670abf3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyOptions.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Options to configure a vector store static chunking strategy. + public partial class VectorStoreStaticChunkingStrategyOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 and the maximum value is 4096. + /// + /// The number of tokens that overlap between chunks. The default value is 400. + /// Note that the overlap must not exceed half of max_chunk_size_tokens. * + /// + public VectorStoreStaticChunkingStrategyOptions(int maxChunkSizeTokens, int chunkOverlapTokens) + { + MaxChunkSizeTokens = maxChunkSizeTokens; + ChunkOverlapTokens = chunkOverlapTokens; + } + + /// Initializes a new instance of . + /// The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 and the maximum value is 4096. + /// + /// The number of tokens that overlap between chunks. The default value is 400. + /// Note that the overlap must not exceed half of max_chunk_size_tokens. * + /// + /// Keeps track of any properties unknown to the library. + internal VectorStoreStaticChunkingStrategyOptions(int maxChunkSizeTokens, int chunkOverlapTokens, IDictionary serializedAdditionalRawData) + { + MaxChunkSizeTokens = maxChunkSizeTokens; + ChunkOverlapTokens = chunkOverlapTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreStaticChunkingStrategyOptions() + { + } + + /// The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 and the maximum value is 4096. + public int MaxChunkSizeTokens { get; set; } + /// + /// The number of tokens that overlap between chunks. The default value is 400. + /// Note that the overlap must not exceed half of max_chunk_size_tokens. * + /// + public int ChunkOverlapTokens { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.Serialization.cs new file mode 100644 index 000000000000..25e218d5e3ed --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreStaticChunkingStrategyRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyRequest)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("static"u8); + writer.WriteObjectValue(Static, options); + } + + VectorStoreStaticChunkingStrategyRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreStaticChunkingStrategyRequest(document.RootElement, options); + } + + internal static VectorStoreStaticChunkingStrategyRequest DeserializeVectorStoreStaticChunkingStrategyRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreStaticChunkingStrategyOptions @static = default; + VectorStoreChunkingStrategyRequestType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("static"u8)) + { + @static = VectorStoreStaticChunkingStrategyOptions.DeserializeVectorStoreStaticChunkingStrategyOptions(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyRequestType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreStaticChunkingStrategyRequest(type, serializedAdditionalRawData, @static); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyRequest)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreStaticChunkingStrategyRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreStaticChunkingStrategyRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreStaticChunkingStrategyRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreStaticChunkingStrategyRequest(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.cs new file mode 100644 index 000000000000..0a65da2962bd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyRequest.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A statically configured chunking strategy. + public partial class VectorStoreStaticChunkingStrategyRequest : VectorStoreChunkingStrategyRequest + { + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// is null. + public VectorStoreStaticChunkingStrategyRequest(VectorStoreStaticChunkingStrategyOptions @static) + { + Argument.AssertNotNull(@static, nameof(@static)); + + Type = VectorStoreChunkingStrategyRequestType.Static; + Static = @static; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The options for the static chunking strategy. + internal VectorStoreStaticChunkingStrategyRequest(VectorStoreChunkingStrategyRequestType type, IDictionary serializedAdditionalRawData, VectorStoreStaticChunkingStrategyOptions @static) : base(type, serializedAdditionalRawData) + { + Static = @static; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreStaticChunkingStrategyRequest() + { + } + + /// The options for the static chunking strategy. + public VectorStoreStaticChunkingStrategyOptions Static { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.Serialization.cs new file mode 100644 index 000000000000..a116c8ce6fe6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreStaticChunkingStrategyResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyResponse)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("static"u8); + writer.WriteObjectValue(Static, options); + } + + VectorStoreStaticChunkingStrategyResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreStaticChunkingStrategyResponse(document.RootElement, options); + } + + internal static VectorStoreStaticChunkingStrategyResponse DeserializeVectorStoreStaticChunkingStrategyResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + VectorStoreStaticChunkingStrategyOptions @static = default; + VectorStoreChunkingStrategyResponseType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("static"u8)) + { + @static = VectorStoreStaticChunkingStrategyOptions.DeserializeVectorStoreStaticChunkingStrategyOptions(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new VectorStoreChunkingStrategyResponseType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreStaticChunkingStrategyResponse(type, serializedAdditionalRawData, @static); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyResponse)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreStaticChunkingStrategyResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreStaticChunkingStrategyResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreStaticChunkingStrategyResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new VectorStoreStaticChunkingStrategyResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreStaticChunkingStrategyResponse(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.cs new file mode 100644 index 000000000000..5d2a0200bdcd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStaticChunkingStrategyResponse.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI.Assistants +{ + /// A statically configured chunking strategy. + public partial class VectorStoreStaticChunkingStrategyResponse : VectorStoreChunkingStrategyResponse + { + /// Initializes a new instance of . + /// The options for the static chunking strategy. + /// is null. + internal VectorStoreStaticChunkingStrategyResponse(VectorStoreStaticChunkingStrategyOptions @static) + { + Argument.AssertNotNull(@static, nameof(@static)); + + Type = VectorStoreChunkingStrategyResponseType.Static; + Static = @static; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The options for the static chunking strategy. + internal VectorStoreStaticChunkingStrategyResponse(VectorStoreChunkingStrategyResponseType type, IDictionary serializedAdditionalRawData, VectorStoreStaticChunkingStrategyOptions @static) : base(type, serializedAdditionalRawData) + { + Static = @static; + } + + /// Initializes a new instance of for deserialization. + internal VectorStoreStaticChunkingStrategyResponse() + { + } + + /// The options for the static chunking strategy. + public VectorStoreStaticChunkingStrategyOptions Static { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStatus.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStatus.cs new file mode 100644 index 000000000000..d8b1d0e87b45 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreStatus.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI.Assistants +{ + /// Vector store possible status. + public readonly partial struct VectorStoreStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public VectorStoreStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ExpiredValue = "expired"; + private const string InProgressValue = "in_progress"; + private const string CompletedValue = "completed"; + + /// expired status indicates that this vector store has expired and is no longer available for use. + public static VectorStoreStatus Expired { get; } = new VectorStoreStatus(ExpiredValue); + /// in_progress status indicates that this vector store is still processing files. + public static VectorStoreStatus InProgress { get; } = new VectorStoreStatus(InProgressValue); + /// completed status indicates that this vector store is ready for use. + public static VectorStoreStatus Completed { get; } = new VectorStoreStatus(CompletedValue); + /// Determines if two values are the same. + public static bool operator ==(VectorStoreStatus left, VectorStoreStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(VectorStoreStatus left, VectorStoreStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator VectorStoreStatus(string value) => new VectorStoreStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is VectorStoreStatus other && Equals(other); + /// + public bool Equals(VectorStoreStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.Serialization.cs new file mode 100644 index 000000000000..584d6fa01c6a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.Serialization.cs @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI.Assistants +{ + public partial class VectorStoreUpdateOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreUpdateOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Name)) + { + if (Name != null) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + else + { + writer.WriteNull("name"); + } + } + if (Optional.IsDefined(ExpiresAfter)) + { + if (ExpiresAfter != null) + { + writer.WritePropertyName("expires_after"u8); + writer.WriteObjectValue(ExpiresAfter, options); + } + else + { + writer.WriteNull("expires_after"); + } + } + if (Optional.IsCollectionDefined(Metadata)) + { + if (Metadata != null) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + else + { + writer.WriteNull("metadata"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + VectorStoreUpdateOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(VectorStoreUpdateOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeVectorStoreUpdateOptions(document.RootElement, options); + } + + internal static VectorStoreUpdateOptions DeserializeVectorStoreUpdateOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + VectorStoreExpirationPolicy expiresAfter = default; + IDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + name = null; + continue; + } + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("expires_after"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + expiresAfter = null; + continue; + } + expiresAfter = VectorStoreExpirationPolicy.DeserializeVectorStoreExpirationPolicy(property.Value, options); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new VectorStoreUpdateOptions(name, expiresAfter, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(VectorStoreUpdateOptions)} does not support writing '{options.Format}' format."); + } + } + + VectorStoreUpdateOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreUpdateOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(VectorStoreUpdateOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static VectorStoreUpdateOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeVectorStoreUpdateOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.cs b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.cs similarity index 69% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.cs rename to sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.cs index 46ab2f35dbcb..e3bcef35dc48 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/UpdateThreadRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/VectorStoreUpdateOptions.cs @@ -10,8 +10,8 @@ namespace Azure.AI.OpenAI.Assistants { - /// The UpdateThreadRequest. - internal partial class UpdateThreadRequest + /// Request object for updating a vector store. + public partial class VectorStoreUpdateOptions { /// /// Keeps track of any properties unknown to the library. @@ -45,22 +45,30 @@ internal partial class UpdateThreadRequest /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - internal UpdateThreadRequest() + /// Initializes a new instance of . + public VectorStoreUpdateOptions() { Metadata = new ChangeTrackingDictionary(); } - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The name of the vector store. + /// Details on when this vector store expires. /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. /// Keeps track of any properties unknown to the library. - internal UpdateThreadRequest(IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + internal VectorStoreUpdateOptions(string name, VectorStoreExpirationPolicy expiresAfter, IDictionary metadata, IDictionary serializedAdditionalRawData) { + Name = name; + ExpiresAfter = expiresAfter; Metadata = metadata; _serializedAdditionalRawData = serializedAdditionalRawData; } + /// The name of the vector store. + public string Name { get; set; } + /// Details on when this vector store expires. + public VectorStoreExpirationPolicy ExpiresAfter { get; set; } /// A set of up to 16 key/value pairs that can be attached to an object, used for storing additional information about that object in a structured format. Keys may be up to 64 characters in length and values may be up to 512 characters in length. - public IReadOnlyDictionary Metadata { get; } + public IDictionary Metadata { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml b/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml index 18c498cc098e..2fc1cb79dab3 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml +++ b/sdk/openai/Azure.AI.OpenAI.Assistants/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/ai/OpenAI.Assistants -commit: 08ed77edf1aca430f3f368c848ccd43219bf2ff2 +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIClientBuilderExtensions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIClientBuilderExtensions.cs new file mode 100644 index 000000000000..bc32a7f2b1a4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIClientBuilderExtensions.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure; +using Azure.AI.OpenAI; +using Azure.Core.Extensions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class AIOpenAIClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + public static IAzureClientBuilder AddOpenAIClient(this TBuilder builder, Uri endpoint, AzureKeyCredential credential) + where TBuilder : IAzureClientFactoryBuilder + { + return builder.RegisterClientFactory((options) => new OpenAIClient(endpoint, credential, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + public static IAzureClientBuilder AddOpenAIClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new OpenAIClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddOpenAIClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIModelFactory.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIModelFactory.cs new file mode 100644 index 000000000000..fa7196db6f7d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AIOpenAIModelFactory.cs @@ -0,0 +1,1620 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Model factory for models. + public static partial class AIOpenAIModelFactory + { + /// Initializes a new instance of . + /// + /// 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. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the transcription response data, which will influence the content and detail of the result. + /// + /// The primary spoken language of the audio data to be transcribed, supplied as a two-letter ISO-639-1 language code + /// such as 'en' or 'fr'. + /// Providing this known input language is optional but may improve the accuracy and/or latency of transcription. + /// + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// 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. + /// + /// + /// The timestamp granularities to populate for this transcription. + /// `response_format` must be set `verbose_json` to use timestamp granularities. + /// Either or both of these options are supported: `word`, or `segment`. + /// Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + /// + /// The model to use for this transcription request. + /// A new instance for mocking. + public static AudioTranscriptionOptions AudioTranscriptionOptions(Stream audioData = null, string filename = null, AudioTranscriptionFormat? responseFormat = null, string language = null, string prompt = null, float? temperature = null, IEnumerable timestampGranularities = null, string deploymentName = null) + { + timestampGranularities ??= new List(); + + return new AudioTranscriptionOptions( + audioData, + filename, + responseFormat, + language, + prompt, + temperature, + timestampGranularities?.ToList(), + deploymentName, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a transcription. + /// The time at which this segment started relative to the beginning of the transcribed audio. + /// The time at which this segment ended relative to the beginning of the transcribed audio. + /// The transcribed text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the transcribed text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// A new instance for mocking. + public static AudioTranscriptionSegment AudioTranscriptionSegment(int id = default, TimeSpan start = default, TimeSpan end = default, string text = null, float temperature = default, float averageLogProbability = default, float compressionRatio = default, float noSpeechProbability = default, IEnumerable tokens = null, int seek = default) + { + tokens ??= new List(); + + return new AudioTranscriptionSegment( + id, + start, + end, + text, + temperature, + averageLogProbability, + compressionRatio, + noSpeechProbability, + tokens?.ToList(), + seek, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The textual content of the word. + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + /// A new instance for mocking. + public static AudioTranscriptionWord AudioTranscriptionWord(string word = null, TimeSpan start = default, TimeSpan end = default) + { + return new AudioTranscriptionWord(word, start, end, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the translation response data, which will influence the content and detail of the result. + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// 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. + /// + /// The model to use for this translation request. + /// A new instance for mocking. + public static AudioTranslationOptions AudioTranslationOptions(Stream audioData = null, string filename = null, AudioTranslationFormat? responseFormat = null, string prompt = null, float? temperature = null, string deploymentName = null) + { + return new AudioTranslationOptions( + audioData, + filename, + responseFormat, + prompt, + temperature, + deploymentName, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a translation. + /// The time at which this segment started relative to the beginning of the translated audio. + /// The time at which this segment ended relative to the beginning of the translated audio. + /// The translated text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the translated text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// A new instance for mocking. + public static AudioTranslationSegment AudioTranslationSegment(int id = default, TimeSpan start = default, TimeSpan end = default, string text = null, float temperature = default, float averageLogProbability = default, float compressionRatio = default, float noSpeechProbability = default, IEnumerable tokens = null, int seek = default) + { + tokens ??= new List(); + + return new AudioTranslationSegment( + id, + start, + end, + text, + temperature, + averageLogProbability, + compressionRatio, + noSpeechProbability, + tokens?.ToList(), + seek, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A unique identifier associated with this completions response. + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// 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. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// + /// This fingerprint represents the backend configuration that the model runs with. + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + /// + /// A new instance for mocking. + public static Completions Completions(string id = null, DateTimeOffset created = default, IEnumerable promptFilterResults = null, IEnumerable choices = null, CompletionsUsage usage = null, string systemFingerprint = null) + { + promptFilterResults ??= new List(); + choices ??= new List(); + + return new Completions( + id, + created, + promptFilterResults?.ToList(), + choices?.ToList(), + usage, + systemFingerprint, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The index of this prompt in the set of prompt results. + /// Content filtering results for this prompt. + /// A new instance for mocking. + public static ContentFilterResultsForPrompt ContentFilterResultsForPrompt(int promptIndex = default, ContentFilterResultDetailsForPrompt contentFilterResults = null) + { + return new ContentFilterResultsForPrompt(promptIndex, contentFilterResults, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Whether a jailbreak attempt was detected in the prompt. + /// Whether an indirect attack was detected in the prompt. + /// A new instance for mocking. + public static ContentFilterResultDetailsForPrompt ContentFilterResultDetailsForPrompt(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null, ContentFilterDetectionResult profanity = null, ContentFilterDetailedResults customBlocklists = null, ResponseError error = null, ContentFilterDetectionResult jailbreak = null, ContentFilterDetectionResult indirectAttack = null) + { + return new ContentFilterResultDetailsForPrompt( + sexual, + violence, + hate, + selfHarm, + profanity, + customBlocklists, + error, + jailbreak, + indirectAttack, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// Ratings for the intensity and risk level of filtered content. + /// A new instance for mocking. + public static ContentFilterResult ContentFilterResult(bool filtered = default, ContentFilterSeverity severity = default) + { + return new ContentFilterResult(filtered, severity, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// A new instance for mocking. + public static ContentFilterDetectionResult ContentFilterDetectionResult(bool filtered = default, bool detected = default) + { + return new ContentFilterDetectionResult(filtered, detected, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The collection of detailed blocklist result information. + /// A new instance for mocking. + public static ContentFilterDetailedResults ContentFilterDetailedResults(bool filtered = default, IEnumerable details = null) + { + details ??= new List(); + + return new ContentFilterDetailedResults(filtered, details?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The ID of the custom blocklist evaluated. + /// A new instance for mocking. + public static ContentFilterBlocklistIdResult ContentFilterBlocklistIdResult(bool filtered = default, string id = null) + { + return new ContentFilterBlocklistIdResult(filtered, id, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The generated text for a given completions prompt. + /// The ordered index associated with this completions choice. + /// + /// 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. + /// + /// The log probabilities model for tokens associated with this completions choice. + /// Reason for finishing. + /// A new instance for mocking. + public static Choice Choice(string text = null, int index = default, ContentFilterResultsForChoice contentFilterResults = null, CompletionsLogProbabilityModel logProbabilityModel = null, CompletionsFinishReason? finishReason = null) + { + return new Choice( + text, + index, + contentFilterResults, + logProbabilityModel, + finishReason, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Information about detection of protected text material. + /// Information about detection of protected code material. + /// Information about detection of ungrounded material. + /// A new instance for mocking. + public static ContentFilterResultsForChoice ContentFilterResultsForChoice(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null, ContentFilterDetectionResult profanity = null, ContentFilterDetailedResults customBlocklists = null, ResponseError error = null, ContentFilterDetectionResult protectedMaterialText = null, ContentFilterCitedDetectionResult protectedMaterialCode = null, ContentFilterCompletionTextSpanResult ungroundedMaterial = null) + { + return new ContentFilterResultsForChoice( + sexual, + violence, + hate, + selfHarm, + profanity, + customBlocklists, + error, + protectedMaterialText, + protectedMaterialCode, + ungroundedMaterial, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// The internet location associated with the detection. + /// The license description associated with the detection. + /// A new instance for mocking. + public static ContentFilterCitedDetectionResult ContentFilterCitedDetectionResult(bool filtered = default, bool detected = default, Uri url = null, string license = null) + { + return new ContentFilterCitedDetectionResult(filtered, detected, url, license, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// The collection of completion text spans. + /// A new instance for mocking. + public static ContentFilterCompletionTextSpanResult ContentFilterCompletionTextSpanResult(bool filtered = default, bool detected = default, IEnumerable details = null) + { + details ??= new List(); + + return new ContentFilterCompletionTextSpanResult(filtered, detected, details?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Offset of the UTF32 code point which begins the span. + /// + /// Offset of the first UTF32 code point which is excluded from the span. + /// This field is always equal to completion_start_offset for empty spans. + /// This field is always larger than completion_start_offset for non-empty spans. + /// + /// A new instance for mocking. + public static ContentFilterCompletionTextSpan ContentFilterCompletionTextSpan(int completionStartOffset = default, int completionEndOffset = default) + { + return new ContentFilterCompletionTextSpan(completionStartOffset, completionEndOffset, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The textual forms of tokens evaluated in this probability model. + /// A collection of log probability values for the tokens in this completions data. + /// A mapping of tokens to maximum log probability values in this completions data. + /// The text offsets associated with tokens in this completions data. + /// A new instance for mocking. + public static CompletionsLogProbabilityModel CompletionsLogProbabilityModel(IEnumerable tokens = null, IEnumerable tokenLogProbabilities = null, IEnumerable> topLogProbabilities = null, IEnumerable textOffsets = null) + { + tokens ??= new List(); + tokenLogProbabilities ??= new List(); + topLogProbabilities ??= new List>(); + textOffsets ??= new List(); + + return new CompletionsLogProbabilityModel(tokens?.ToList(), tokenLogProbabilities?.ToList(), topLogProbabilities?.ToList(), textOffsets?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The number of tokens generated across all completions emissions. + /// The number of tokens in the provided prompts for the completions request. + /// The total number of tokens processed for the completions request and response. + /// Details of the prompt tokens. + /// Breakdown of tokens used in a completion. + /// A new instance for mocking. + public static CompletionsUsage CompletionsUsage(int completionTokens = default, int promptTokens = default, int totalTokens = default, CompletionsUsagePromptTokensDetails promptTokensDetails = null, CompletionsUsageCompletionTokensDetails completionTokensDetails = null) + { + return new CompletionsUsage( + completionTokens, + promptTokens, + totalTokens, + promptTokensDetails, + completionTokensDetails, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Audio input tokens present in the prompt. + /// Cached tokens present in the prompt. + /// A new instance for mocking. + public static CompletionsUsagePromptTokensDetails CompletionsUsagePromptTokensDetails(int? audioTokens = null, int? cachedTokens = null) + { + return new CompletionsUsagePromptTokensDetails(audioTokens, cachedTokens, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// When using Predicted Outputs, the number of tokens in the + /// prediction that appeared in the completion. + /// + /// Audio input tokens generated by the model. + /// Tokens generated by the model for reasoning. + /// + /// When using Predicted Outputs, the number of tokens in the + /// prediction that did not appear in the completion. However, like + /// reasoning tokens, these tokens are still counted in the total + /// completion tokens for purposes of billing, output, and context + /// window limits. + /// + /// A new instance for mocking. + public static CompletionsUsageCompletionTokensDetails CompletionsUsageCompletionTokensDetails(int? acceptedPredictionTokens = null, int? audioTokens = null, int? reasoningTokens = null, int? rejectedPredictionTokens = null) + { + return new CompletionsUsageCompletionTokensDetails(acceptedPredictionTokens, audioTokens, reasoningTokens, rejectedPredictionTokens, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The contents of the system message. + /// An optional name for the participant. + /// A new instance for mocking. + public static ChatRequestSystemMessage ChatRequestSystemMessage(BinaryData content = null, string name = null) + { + return new ChatRequestSystemMessage(ChatRole.System, serializedAdditionalRawData: null, content, name); + } + + /// Initializes a new instance of . + /// The content of the message. + /// A new instance for mocking. + public static ChatMessageTextContentItem ChatMessageTextContentItem(string text = null) + { + return new ChatMessageTextContentItem("text", serializedAdditionalRawData: null, text); + } + + /// Initializes a new instance of . + /// The refusal message. + /// A new instance for mocking. + public static ChatMessageRefusalContentItem ChatMessageRefusalContentItem(string refusal = null) + { + return new ChatMessageRefusalContentItem("refusal", serializedAdditionalRawData: null, refusal); + } + + /// Initializes a new instance of . + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + /// A new instance for mocking. + public static ChatMessageImageContentItem ChatMessageImageContentItem(ChatMessageImageUrl imageUrl = null) + { + return new ChatMessageImageContentItem("image_url", serializedAdditionalRawData: null, imageUrl); + } + + /// Initializes a new instance of . + /// The URL of the image. + /// + /// The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and + /// accuracy. + /// + /// A new instance for mocking. + public static ChatMessageImageUrl ChatMessageImageUrl(Uri url = null, ChatMessageImageDetailLevel? detail = null) + { + return new ChatMessageImageUrl(url, detail, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The audio data. + /// A new instance for mocking. + public static ChatMessageAudioContentItem ChatMessageAudioContentItem(InputAudioContent inputAudio = null) + { + return new ChatMessageAudioContentItem("input_audio", serializedAdditionalRawData: null, inputAudio); + } + + /// Initializes a new instance of . + /// An array of content parts with a defined type. For developer messages, only type `text` is supported. + /// An optional name for the participant. Provides the model information to differentiate between participants of the same role. + /// A new instance for mocking. + public static ChatRequestDeveloperMessage ChatRequestDeveloperMessage(BinaryData content = null, string name = null) + { + return new ChatRequestDeveloperMessage(ChatRole.Developer, serializedAdditionalRawData: null, content, name); + } + + /// Initializes a new instance of . + /// The contents of the user message, with available input types varying by selected model. + /// An optional name for the participant. + /// A new instance for mocking. + public static ChatRequestUserMessage ChatRequestUserMessage(BinaryData content = null, string name = null) + { + return new ChatRequestUserMessage(ChatRole.User, serializedAdditionalRawData: null, content, name); + } + + /// Initializes a new instance of . + /// The content of the message. + /// An optional name for the participant. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// 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. + /// + /// The refusal message by the assistant. + /// A new instance for mocking. + public static ChatRequestAssistantMessage ChatRequestAssistantMessage(BinaryData content = null, string name = null, IEnumerable toolCalls = null, FunctionCall functionCall = null, string refusal = null) + { + toolCalls ??= new List(); + + return new ChatRequestAssistantMessage( + ChatRole.Assistant, + serializedAdditionalRawData: null, + content, + name, + toolCalls?.ToList(), + functionCall, + refusal); + } + + /// Initializes a new instance of . + /// The content of the message. + /// The ID of the tool call resolved by the provided content. + /// A new instance for mocking. + public static ChatRequestToolMessage ChatRequestToolMessage(BinaryData content = null, string toolCallId = null) + { + return new ChatRequestToolMessage(ChatRole.Tool, serializedAdditionalRawData: null, content, toolCallId); + } + + /// Initializes a new instance of . + /// The name of the function that was called to produce output. + /// The output of the function as requested by the function call. + /// A new instance for mocking. + public static ChatRequestFunctionMessage ChatRequestFunctionMessage(string name = null, string content = null) + { + return new ChatRequestFunctionMessage(ChatRole.Function, serializedAdditionalRawData: null, name, content); + } + + /// Initializes a new instance of . + /// The name of the function to be called. + /// + /// A description of what the function does. The model will use this description when selecting the function and + /// interpreting its parameters. + /// + /// The parameters the function accepts, described as a JSON Schema object. + /// A new instance for mocking. + public static FunctionDefinition FunctionDefinition(string name = null, string description = null, BinaryData parameters = null) + { + return new FunctionDefinition(name, description, parameters, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Azure Search. + /// A new instance for mocking. + public static AzureSearchChatExtensionConfiguration AzureSearchChatExtensionConfiguration(AzureSearchChatExtensionParameters parameters = null) + { + return new AzureSearchChatExtensionConfiguration(AzureChatExtensionType.AzureSearch, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + /// Customized field mapping behavior to use when interacting with the search index. + /// The query type to use with Azure Cognitive Search. + /// The additional semantic configuration for the query. + /// Search filter. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static AzureSearchChatExtensionParameters AzureSearchChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, Uri searchEndpoint = null, string indexName = null, AzureSearchIndexFieldMappingOptions fieldMappingOptions = null, AzureSearchQueryType? queryType = null, string semanticConfiguration = null, string filter = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new AzureSearchChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + searchEndpoint, + indexName, + fieldMappingOptions, + queryType, + semanticConfiguration, + filter, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The API key to use for authentication. + /// A new instance for mocking. + public static OnYourDataApiKeyAuthenticationOptions OnYourDataApiKeyAuthenticationOptions(string key = null) + { + return new OnYourDataApiKeyAuthenticationOptions(OnYourDataAuthenticationType.ApiKey, serializedAdditionalRawData: null, key); + } + + /// Initializes a new instance of . + /// The connection string to use for authentication. + /// A new instance for mocking. + public static OnYourDataConnectionStringAuthenticationOptions OnYourDataConnectionStringAuthenticationOptions(string connectionString = null) + { + return new OnYourDataConnectionStringAuthenticationOptions(OnYourDataAuthenticationType.ConnectionString, serializedAdditionalRawData: null, connectionString); + } + + /// Initializes a new instance of . + /// The key to use for authentication. + /// The key ID to use for authentication. + /// A new instance for mocking. + public static OnYourDataKeyAndKeyIdAuthenticationOptions OnYourDataKeyAndKeyIdAuthenticationOptions(string key = null, string keyId = null) + { + return new OnYourDataKeyAndKeyIdAuthenticationOptions(OnYourDataAuthenticationType.KeyAndKeyId, serializedAdditionalRawData: null, key, keyId); + } + + /// Initializes a new instance of . + /// The encoded API key to use for authentication. + /// A new instance for mocking. + public static OnYourDataEncodedApiKeyAuthenticationOptions OnYourDataEncodedApiKeyAuthenticationOptions(string encodedApiKey = null) + { + return new OnYourDataEncodedApiKeyAuthenticationOptions(OnYourDataAuthenticationType.EncodedApiKey, serializedAdditionalRawData: null, encodedApiKey); + } + + /// Initializes a new instance of . + /// The username. + /// The password. + /// A new instance for mocking. + public static OnYourDataUsernameAndPasswordAuthenticationOptions OnYourDataUsernameAndPasswordAuthenticationOptions(string username = null, string password = null) + { + return new OnYourDataUsernameAndPasswordAuthenticationOptions(OnYourDataAuthenticationType.UsernameAndPassword, serializedAdditionalRawData: null, username, password); + } + + /// Initializes a new instance of . + /// The access token to use for authentication. + /// A new instance for mocking. + public static OnYourDataAccessTokenAuthenticationOptions OnYourDataAccessTokenAuthenticationOptions(string accessToken = null) + { + return new OnYourDataAccessTokenAuthenticationOptions(OnYourDataAuthenticationType.AccessToken, serializedAdditionalRawData: null, accessToken); + } + + /// Initializes a new instance of . + /// The resource ID of the user-assigned managed identity to use for authentication. + /// A new instance for mocking. + public static OnYourDataUserAssignedManagedIdentityAuthenticationOptions OnYourDataUserAssignedManagedIdentityAuthenticationOptions(string managedIdentityResourceId = null) + { + return new OnYourDataUserAssignedManagedIdentityAuthenticationOptions(OnYourDataAuthenticationType.UserAssignedManagedIdentity, serializedAdditionalRawData: null, managedIdentityResourceId); + } + + /// Initializes a new instance of . + /// 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. + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// A new instance for mocking. + public static OnYourDataEndpointVectorizationSource OnYourDataEndpointVectorizationSource(Uri endpoint = null, OnYourDataVectorSearchAuthenticationOptions authentication = null) + { + return new OnYourDataEndpointVectorizationSource(OnYourDataVectorizationSourceType.Endpoint, serializedAdditionalRawData: null, endpoint, authentication); + } + + /// Initializes a new instance of . + /// The API key to use for authentication. + /// A new instance for mocking. + public static OnYourDataVectorSearchApiKeyAuthenticationOptions OnYourDataVectorSearchApiKeyAuthenticationOptions(string key = null) + { + return new OnYourDataVectorSearchApiKeyAuthenticationOptions(OnYourDataVectorSearchAuthenticationType.ApiKey, serializedAdditionalRawData: null, key); + } + + /// Initializes a new instance of . + /// The access token to use for authentication. + /// A new instance for mocking. + public static OnYourDataVectorSearchAccessTokenAuthenticationOptions OnYourDataVectorSearchAccessTokenAuthenticationOptions(string accessToken = null) + { + return new OnYourDataVectorSearchAccessTokenAuthenticationOptions(OnYourDataVectorSearchAuthenticationType.AccessToken, serializedAdditionalRawData: null, accessToken); + } + + /// Initializes a new instance of . + /// 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. + /// The number of dimensions the embeddings should have. Only supported in `text-embedding-3` and later models. + /// A new instance for mocking. + public static OnYourDataDeploymentNameVectorizationSource OnYourDataDeploymentNameVectorizationSource(string deploymentName = null, int? dimensions = null) + { + return new OnYourDataDeploymentNameVectorizationSource(OnYourDataVectorizationSourceType.DeploymentName, serializedAdditionalRawData: null, deploymentName, dimensions); + } + + /// Initializes a new instance of . + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + /// A new instance for mocking. + public static OnYourDataModelIdVectorizationSource OnYourDataModelIdVectorizationSource(string modelId = null) + { + return new OnYourDataModelIdVectorizationSource(OnYourDataVectorizationSourceType.ModelId, serializedAdditionalRawData: null, modelId); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + /// A new instance for mocking. + public static AzureCosmosDBChatExtensionConfiguration AzureCosmosDBChatExtensionConfiguration(AzureCosmosDBChatExtensionParameters parameters = null) + { + return new AzureCosmosDBChatExtensionConfiguration(AzureChatExtensionType.AzureCosmosDB, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The MongoDB vCore database name to use with Azure Cosmos DB. + /// The name of the Azure Cosmos DB resource container. + /// The MongoDB vCore index name to use with Azure Cosmos DB. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static AzureCosmosDBChatExtensionParameters AzureCosmosDBChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, string databaseName = null, string containerName = null, string indexName = null, AzureCosmosDBFieldMappingOptions fieldMappingOptions = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new AzureCosmosDBChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + databaseName, + containerName, + indexName, + fieldMappingOptions, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Elasticsearch®. + /// A new instance for mocking. + public static ElasticsearchChatExtensionConfiguration ElasticsearchChatExtensionConfiguration(ElasticsearchChatExtensionParameters parameters = null) + { + return new ElasticsearchChatExtensionConfiguration(AzureChatExtensionType.Elasticsearch, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The endpoint of Elasticsearch®. + /// The index name of Elasticsearch®. + /// The index field mapping options of Elasticsearch®. + /// The query type of Elasticsearch®. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static ElasticsearchChatExtensionParameters ElasticsearchChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, Uri endpoint = null, string indexName = null, ElasticsearchIndexFieldMappingOptions fieldMappingOptions = null, ElasticsearchQueryType? queryType = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new ElasticsearchChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + endpoint, + indexName, + fieldMappingOptions, + queryType, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters for the MongoDB chat extension. + /// A new instance for mocking. + public static MongoDBChatExtensionConfiguration MongoDBChatExtensionConfiguration(MongoDBChatExtensionParameters parameters = null) + { + return new MongoDBChatExtensionConfiguration(AzureChatExtensionType.MongoDB, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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 endpoint name for MongoDB. + /// The collection name for MongoDB. + /// The database name for MongoDB. + /// The app name for MongoDB. + /// The name of the MongoDB index. + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + /// The vectorization source to use with the MongoDB chat extension. + /// A new instance for mocking. + public static MongoDBChatExtensionParameters MongoDBChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataUsernameAndPasswordAuthenticationOptions authentication = null, string endpoint = null, string collectionName = null, string databaseName = null, string appName = null, string indexName = null, MongoDBChatExtensionParametersFieldsMapping fieldsMapping = null, BinaryData embeddingDependency = null) + { + includeContexts ??= new List(); + + return new MongoDBChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + endpoint, + collectionName, + databaseName, + appName, + indexName, + fieldsMapping, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI chat extensions. + /// A new instance for mocking. + public static PineconeChatExtensionConfiguration PineconeChatExtensionConfiguration(PineconeChatExtensionParameters parameters = null) + { + return new PineconeChatExtensionConfiguration(AzureChatExtensionType.Pinecone, serializedAdditionalRawData: null, parameters); + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The environment name of Pinecone. + /// The name of the Pinecone database index. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// A new instance for mocking. + public static PineconeChatExtensionParameters PineconeChatExtensionParameters(int? documentCount = null, bool? shouldRestrictResultScope = null, int? strictness = null, int? maxSearchQueries = null, bool? allowPartialResult = null, IEnumerable includeContexts = null, OnYourDataAuthenticationOptions authentication = null, string environmentName = null, string indexName = null, PineconeFieldMappingOptions fieldMappingOptions = null, OnYourDataVectorizationSource embeddingDependency = null) + { + includeContexts ??= new List(); + + return new PineconeChatExtensionParameters( + documentCount, + shouldRestrictResultScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts?.ToList(), + authentication, + environmentName, + indexName, + fieldMappingOptions, + embeddingDependency, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// A new instance for mocking. + public static ChatCompletionsJsonSchemaResponseFormat ChatCompletionsJsonSchemaResponseFormat(ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema = null) + { + return new ChatCompletionsJsonSchemaResponseFormat("json_schema", serializedAdditionalRawData: null, jsonSchema); + } + + /// Initializes a new instance of . + /// A description of what the response format is for, used by the model to determine how to respond in the format. + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + /// A new instance for mocking. + public static ChatCompletionsJsonSchemaResponseFormatJsonSchema ChatCompletionsJsonSchemaResponseFormatJsonSchema(string description = null, string name = null, BinaryData schema = null, bool? strict = null) + { + return new ChatCompletionsJsonSchemaResponseFormatJsonSchema(description, name, schema, strict, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The function definition details for the function tool. + /// A new instance for mocking. + public static ChatCompletionsFunctionToolDefinition ChatCompletionsFunctionToolDefinition(ChatCompletionsFunctionToolDefinitionFunction function = null) + { + return new ChatCompletionsFunctionToolDefinition("function", serializedAdditionalRawData: null, function); + } + + /// Initializes a new instance of . + /// A description of what the function does, used by the model to choose when and how to call the function. + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + /// A new instance for mocking. + public static ChatCompletionsFunctionToolDefinitionFunction ChatCompletionsFunctionToolDefinitionFunction(string description = null, string name = null, BinaryData parameters = null, bool? strict = null) + { + return new ChatCompletionsFunctionToolDefinitionFunction(description, name, parameters, strict, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The function that should be called. + /// A new instance for mocking. + public static ChatCompletionsNamedFunctionToolSelection ChatCompletionsNamedFunctionToolSelection(ChatCompletionsFunctionToolSelection function = null) + { + return new ChatCompletionsNamedFunctionToolSelection("function", serializedAdditionalRawData: null, function); + } + + /// Initializes a new instance of . + /// + /// The type of the predicted content you want to provide. This type is + /// currently always `content`. + /// + /// + /// The content that should be matched when generating a model response. + /// If generated tokens would match this content, the entire model response + /// can be returned much more quickly. + /// + /// A new instance for mocking. + public static PredictionContent PredictionContent(PredictionContentType type = default, BinaryData content = null) + { + return new PredictionContent(type, content, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// A unique identifier associated with this chat completions response. + /// + /// 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. + /// + /// + /// 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. + /// + /// The model name used for this completions request. + /// + /// 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. + /// + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that + /// might impact determinism. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// A new instance for mocking. + public static ChatCompletions ChatCompletions(string id = null, DateTimeOffset created = default, IEnumerable choices = null, string model = null, IEnumerable promptFilterResults = null, string systemFingerprint = null, CompletionsUsage usage = null) + { + choices ??= new List(); + promptFilterResults ??= new List(); + + return new ChatCompletions( + id, + created, + choices?.ToList(), + model, + promptFilterResults?.ToList(), + systemFingerprint, + usage, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The chat message for a given chat completions prompt. + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + /// The ordered index associated with this chat completions choice. + /// The reason that this chat completions choice completed its generated. + /// The delta message content for a streaming response. + /// + /// 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. + /// + /// + /// 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. + /// + /// A new instance for mocking. + public static ChatChoice ChatChoice(ChatResponseMessage message = null, ChatChoiceLogProbabilityInfo logProbabilityInfo = null, int index = default, CompletionsFinishReason? finishReason = null, ChatResponseMessage internalStreamingDeltaMessage = null, ContentFilterResultsForChoice contentFilterResults = null, AzureChatEnhancements enhancements = null) + { + return new ChatChoice( + message, + logProbabilityInfo, + index, + finishReason, + internalStreamingDeltaMessage, + contentFilterResults, + enhancements, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The chat role associated with the message. + /// The refusal message generated by the model. + /// The content of the message. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// 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. + /// + /// + /// If the audio output modality is requested, this object contains data + /// about the audio response from the model. + /// + /// + /// If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those + /// extensions while processing the chat completions request. + /// + /// A new instance for mocking. + public static ChatResponseMessage ChatResponseMessage(ChatRole role = default, string refusal = null, string content = null, IEnumerable toolCalls = null, FunctionCall functionCall = null, AudioResponseData audio = null, AzureChatExtensionsMessageContext azureExtensionsContext = null) + { + toolCalls ??= new List(); + + return new ChatResponseMessage( + role, + refusal, + content, + toolCalls?.ToList(), + functionCall, + audio, + azureExtensionsContext, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Unique identifier for this audio response. + /// + /// The Unix timestamp (in seconds) for when this audio response + /// will no longer be accessible on the server for use in multi-turn + /// conversations. + /// + /// + /// Base64 encoded audio bytes generated by the model, in the format + /// specified in the request. + /// + /// Transcript of the audio generated by the model. + /// A new instance for mocking. + public static AudioResponseData AudioResponseData(string id = null, DateTimeOffset expiresAt = default, string data = null, string transcript = null) + { + return new AudioResponseData(id, expiresAt, data, transcript, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// The contextual information 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. + /// + /// The detected intent from the chat history, used to pass to the next turn to carry over the context. + /// All the retrieved documents. + /// A new instance for mocking. + public static AzureChatExtensionsMessageContext AzureChatExtensionsMessageContext(IEnumerable citations = null, string intent = null, IEnumerable allRetrievedDocuments = null) + { + citations ??= new List(); + allRetrievedDocuments ??= new List(); + + return new AzureChatExtensionsMessageContext(citations?.ToList(), intent, allRetrievedDocuments?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The content of the citation. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. + /// A new instance for mocking. + public static AzureChatExtensionDataSourceResponseCitation AzureChatExtensionDataSourceResponseCitation(string content = null, string title = null, string url = null, string filepath = null, string chunkId = null, double? rerankScore = null) + { + return new AzureChatExtensionDataSourceResponseCitation( + content, + title, + url, + filepath, + chunkId, + rerankScore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The content of the citation. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. + /// The search queries used to retrieve the document. + /// The index of the data source. + /// The original search score of the retrieved document. + /// + /// Represents the rationale for filtering the document. If the document does not undergo filtering, + /// this field will remain unset. + /// + /// A new instance for mocking. + public static AzureChatExtensionRetrievedDocument AzureChatExtensionRetrievedDocument(string content = null, string title = null, string url = null, string filepath = null, string chunkId = null, double? rerankScore = null, IEnumerable searchQueries = null, int dataSourceIndex = default, double? originalSearchScore = null, AzureChatExtensionRetrieveDocumentFilterReason? filterReason = null) + { + searchQueries ??= new List(); + + return new AzureChatExtensionRetrievedDocument( + content, + title, + url, + filepath, + chunkId, + rerankScore, + searchQueries?.ToList(), + dataSourceIndex, + originalSearchScore, + filterReason, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + /// A new instance for mocking. + public static ChatChoiceLogProbabilityInfo ChatChoiceLogProbabilityInfo(IEnumerable tokenLogProbabilityResults = null, IEnumerable refusal = null) + { + tokenLogProbabilityResults ??= new List(); + refusal ??= new List(); + + return new ChatChoiceLogProbabilityInfo(tokenLogProbabilityResults?.ToList(), refusal?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + /// A new instance for mocking. + public static ChatTokenLogProbabilityResult ChatTokenLogProbabilityResult(string token = null, float logProbability = default, IEnumerable utf8ByteValues = null, IEnumerable topLogProbabilityEntries = null) + { + utf8ByteValues ??= new List(); + topLogProbabilityEntries ??= new List(); + + return new ChatTokenLogProbabilityResult(token, logProbability, utf8ByteValues?.ToList(), topLogProbabilityEntries?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// A new instance for mocking. + public static ChatTokenLogProbabilityInfo ChatTokenLogProbabilityInfo(string token = null, float logProbability = default, IEnumerable utf8ByteValues = null) + { + utf8ByteValues ??= new List(); + + return new ChatTokenLogProbabilityInfo(token, logProbability, utf8ByteValues?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The grounding enhancement that returns the bounding box of the objects detected in the image. + /// A new instance for mocking. + public static AzureChatEnhancements AzureChatEnhancements(AzureGroundingEnhancement grounding = null) + { + return new AzureChatEnhancements(grounding, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The lines of text detected by the grounding enhancement. + /// A new instance for mocking. + public static AzureGroundingEnhancement AzureGroundingEnhancement(IEnumerable lines = null) + { + lines ??= new List(); + + return new AzureGroundingEnhancement(lines?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The text within the line. + /// An array of spans that represent detected objects and its bounding box information. + /// A new instance for mocking. + public static AzureGroundingEnhancementLine AzureGroundingEnhancementLine(string text = null, IEnumerable spans = null) + { + spans ??= new List(); + + return new AzureGroundingEnhancementLine(text, spans?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The text content of the span that represents the detected object. + /// + /// 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. + /// + /// The length of the span in characters, measured in Unicode codepoints. + /// An array of objects representing points in the polygon that encloses the detected object. + /// A new instance for mocking. + public static AzureGroundingEnhancementLineSpan AzureGroundingEnhancementLineSpan(string text = null, int offset = default, int length = default, IEnumerable polygon = null) + { + polygon ??= new List(); + + return new AzureGroundingEnhancementLineSpan(text, offset, length, polygon?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The x-coordinate (horizontal axis) of the point. + /// The y-coordinate (vertical axis) of the point. + /// A new instance for mocking. + public static AzureGroundingEnhancementCoordinatePoint AzureGroundingEnhancementCoordinatePoint(float x = default, float y = default) + { + return new AzureGroundingEnhancementCoordinatePoint(x, y, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + /// The images generated by the operation. + /// A new instance for mocking. + public static ImageGenerations ImageGenerations(DateTimeOffset created = default, IEnumerable data = null) + { + data ??= new List(); + + return new ImageGenerations(created, data?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The URL that provides temporary access to download the generated image. + /// The complete data for an image, represented as a base64-encoded string. + /// Information about the content filtering results. + /// + /// 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. + /// + /// + /// 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. Information about jailbreak content and profanity, if it has been detected, + /// and if it has been filtered or not. And information about customer block list, if it has + /// been filtered and its id. + /// + /// A new instance for mocking. + public static ImageGenerationData ImageGenerationData(Uri url = null, string base64Data = null, ImageGenerationContentFilterResults contentFilterResults = null, string revisedPrompt = null, ImageGenerationPromptFilterResults promptFilterResults = null) + { + return new ImageGenerationData( + url, + base64Data, + contentFilterResults, + revisedPrompt, + promptFilterResults, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// A new instance for mocking. + public static ImageGenerationContentFilterResults ImageGenerationContentFilterResults(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null) + { + return new ImageGenerationContentFilterResults(sexual, violence, hate, selfHarm, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Whether a jailbreak attempt was detected in the prompt. + /// Information about customer block lists and if something was detected the associated list ID. + /// A new instance for mocking. + public static ImageGenerationPromptFilterResults ImageGenerationPromptFilterResults(ContentFilterResult sexual = null, ContentFilterResult violence = null, ContentFilterResult hate = null, ContentFilterResult selfHarm = null, ContentFilterDetectionResult profanity = null, ContentFilterDetectionResult jailbreak = null, ContentFilterDetailedResults customBlocklists = null) + { + return new ImageGenerationPromptFilterResults( + sexual, + violence, + hate, + selfHarm, + profanity, + jailbreak, + customBlocklists, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The text to generate audio for. The maximum length is 4096 characters. + /// The voice to use for text-to-speech. + /// The audio output format for the spoken text. By default, the MP3 format will be used. + /// The speed of speech for generated audio. Values are valid in the range from 0.25 to 4.0, with 1.0 the default and higher values corresponding to faster speech. + /// The model to use for this text-to-speech request. + /// A new instance for mocking. + public static SpeechGenerationOptions SpeechGenerationOptions(string input = null, SpeechVoice voice = default, SpeechGenerationResponseFormat? responseFormat = null, float? speed = null, string deploymentName = null) + { + return new SpeechGenerationOptions( + input, + voice, + responseFormat, + speed, + deploymentName, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always 'list'. + /// The files returned for the request. + /// A new instance for mocking. + public static FileListResponse FileListResponse(FileListResponseObject @object = default, IEnumerable data = null) + { + data ??= new List(); + + return new FileListResponse(@object, data?.ToList(), serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always 'file'. + /// The identifier, which can be referenced in API endpoints. + /// The size of the file, in bytes. + /// The name of the file. + /// The Unix timestamp, in seconds, representing when this object was created. + /// The intended purpose of a file. + /// The state of the file. This field is available in Azure OpenAI only. + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. + /// A new instance for mocking. + public static OpenAIFile OpenAIFile(OpenAIFileObject @object = default, string id = null, int bytes = default, string filename = null, DateTimeOffset createdAt = default, FilePurpose purpose = default, FileState? status = null, string statusDetails = null) + { + return new OpenAIFile( + @object, + id, + bytes, + filename, + createdAt, + purpose, + status, + statusDetails, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// A filename to associate with the uploaded data. + /// A new instance for mocking. + public static UploadFileRequest UploadFileRequest(Stream data = null, FilePurpose purpose = default, string filename = null) + { + return new UploadFileRequest(data, purpose, filename, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'file'. + /// A new instance for mocking. + public static FileDeletionStatus FileDeletionStatus(string id = null, bool deleted = default, FileDeletionStatusObject @object = default) + { + return new FileDeletionStatus(id, deleted, @object, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// A new instance for mocking. + public static OpenAIPageableListOfBatch OpenAIPageableListOfBatch(OpenAIPageableListOfBatchObject @object = default, IEnumerable data = null, string firstId = null, string lastId = null, bool? hasMore = null) + { + data ??= new List(); + + return new OpenAIPageableListOfBatch( + @object, + data?.ToList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The API endpoint used by the batch. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + /// A new instance for mocking. + public static BatchCreateRequest BatchCreateRequest(string endpoint = null, string inputFileId = null, string completionWindow = null, IDictionary metadata = null) + { + metadata ??= new Dictionary(); + + return new BatchCreateRequest(endpoint, inputFileId, completionWindow, metadata, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The Upload unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The name of the file to be uploaded. + /// The intended number of bytes to be uploaded. + /// The intended purpose of the file. + /// The status of the Upload. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The object type, which is always "upload". + /// The ready File object after the Upload is completed. + /// A new instance for mocking. + public static Upload Upload(string id = null, DateTimeOffset createdAt = default, string filename = null, long bytes = default, UploadPurpose purpose = default, UploadStatus status = default, DateTimeOffset expiresAt = default, UploadObject? @object = null, OpenAIFile file = null) + { + return new Upload( + id, + createdAt, + filename, + bytes, + purpose, + status, + expiresAt, + @object, + file, + serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The upload Part unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Part was created. + /// The ID of the Upload object that this Part was added to. + /// The object type, which is always `upload.part`. + /// Azure only field. + /// A new instance for mocking. + public static UploadPart UploadPart(string id = null, DateTimeOffset createdAt = default, string uploadId = null, UploadPartObject @object = default, string azureBlockId = null) + { + return new UploadPart( + id, + createdAt, + uploadId, + @object, + azureBlockId, + serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.Serialization.cs new file mode 100644 index 000000000000..22e6ff2fa9da --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.Serialization.cs @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AddUploadPartRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AddUploadPartRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("data"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(Data)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(Data), ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AddUploadPartRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AddUploadPartRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAddUploadPartRequest(document.RootElement, options); + } + + internal static AddUploadPartRequest DeserializeAddUploadPartRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("data"u8)) + { + data = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AddUploadPartRequest(data, serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(Data, "data", "data", "application/octet-stream"); + return content; + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(AddUploadPartRequest)} does not support writing '{options.Format}' format."); + } + } + + AddUploadPartRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAddUploadPartRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AddUploadPartRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AddUploadPartRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAddUploadPartRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.cs new file mode 100644 index 000000000000..9f8e672d50eb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AddUploadPartRequest.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The multipart/form-data request body of a data part addition request for an upload. + public partial class AddUploadPartRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The chunk of bytes for this Part. + /// is null. + public AddUploadPartRequest(Stream data) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data; + } + + /// Initializes a new instance of . + /// The chunk of bytes for this Part. + /// Keeps track of any properties unknown to the library. + internal AddUploadPartRequest(Stream data, IDictionary serializedAdditionalRawData) + { + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AddUploadPartRequest() + { + } + + /// The chunk of bytes for this Part. + public Stream Data { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.Serialization.cs similarity index 59% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.Serialization.cs index fe769e9deb54..a07525f7b53c 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessOutputsTarget.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI { - public partial class LivenessOutputsTarget : IUtf8JsonSerializable, IJsonModel + public partial class AudioOutputParameters : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,20 +28,16 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderW /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(AudioOutputParameters)} does not support writing '{format}' format."); } - writer.WritePropertyName("faceRectangle"u8); - writer.WriteObjectValue(FaceRectangle, options); - writer.WritePropertyName("fileName"u8); - writer.WriteStringValue(FileName); - writer.WritePropertyName("timeOffsetWithinFile"u8); - writer.WriteNumberValue(TimeOffsetWithinFile); - writer.WritePropertyName("imageType"u8); - writer.WriteStringValue(ImageType.ToString()); + writer.WritePropertyName("voice"u8); + writer.WriteStringValue(Voice.ToString()); + writer.WritePropertyName("format"u8); + writer.WriteStringValue(Format.ToString()); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -59,19 +55,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessOutputsTarget IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + AudioOutputParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(AudioOutputParameters)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessOutputsTarget(document.RootElement, options); + return DeserializeAudioOutputParameters(document.RootElement, options); } - internal static LivenessOutputsTarget DeserializeLivenessOutputsTarget(JsonElement element, ModelReaderWriterOptions options = null) + internal static AudioOutputParameters DeserializeAudioOutputParameters(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,32 +75,20 @@ internal static LivenessOutputsTarget DeserializeLivenessOutputsTarget(JsonEleme { return null; } - FaceRectangle faceRectangle = default; - string fileName = default; - int timeOffsetWithinFile = default; - FaceImageType imageType = default; + SpeechVoice voice = default; + OutputAudioFormat format = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("faceRectangle"u8)) + if (property.NameEquals("voice"u8)) { - faceRectangle = FaceRectangle.DeserializeFaceRectangle(property.Value, options); + voice = new SpeechVoice(property.Value.GetString()); continue; } - if (property.NameEquals("fileName"u8)) + if (property.NameEquals("format"u8)) { - fileName = property.Value.GetString(); - continue; - } - if (property.NameEquals("timeOffsetWithinFile"u8)) - { - timeOffsetWithinFile = property.Value.GetInt32(); - continue; - } - if (property.NameEquals("imageType"u8)) - { - imageType = new FaceImageType(property.Value.GetString()); + format = new OutputAudioFormat(property.Value.GetString()); continue; } if (options.Format != "W") @@ -113,46 +97,46 @@ internal static LivenessOutputsTarget DeserializeLivenessOutputsTarget(JsonEleme } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessOutputsTarget(faceRectangle, fileName, timeOffsetWithinFile, imageType, serializedAdditionalRawData); + return new AudioOutputParameters(voice, format, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(AudioOutputParameters)} does not support writing '{options.Format}' format."); } } - LivenessOutputsTarget IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + AudioOutputParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessOutputsTarget(document.RootElement, options); + return DeserializeAudioOutputParameters(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessOutputsTarget)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(AudioOutputParameters)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessOutputsTarget FromResponse(Response response) + internal static AudioOutputParameters FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessOutputsTarget(document.RootElement); + return DeserializeAudioOutputParameters(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.cs new file mode 100644 index 000000000000..b710d4d1f946 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioOutputParameters.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Describes the parameters for audio output. + public partial class AudioOutputParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Specifies the voice type. + /// Specifies the output audio format. + public AudioOutputParameters(SpeechVoice voice, OutputAudioFormat format) + { + Voice = voice; + Format = format; + } + + /// Initializes a new instance of . + /// Specifies the voice type. + /// Specifies the output audio format. + /// Keeps track of any properties unknown to the library. + internal AudioOutputParameters(SpeechVoice voice, OutputAudioFormat format, IDictionary serializedAdditionalRawData) + { + Voice = voice; + Format = format; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioOutputParameters() + { + } + + /// Specifies the voice type. + public SpeechVoice Voice { get; } + /// Specifies the output audio format. + public OutputAudioFormat Format { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.Serialization.cs new file mode 100644 index 000000000000..83e67b496d45 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioResponseData : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioResponseData)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt, "U"); + writer.WritePropertyName("data"u8); + writer.WriteStringValue(Data); + writer.WritePropertyName("transcript"u8); + writer.WriteStringValue(Transcript); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioResponseData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioResponseData)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioResponseData(document.RootElement, options); + } + + internal static AudioResponseData DeserializeAudioResponseData(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset expiresAt = default; + string data = default; + string transcript = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("data"u8)) + { + data = property.Value.GetString(); + continue; + } + if (property.NameEquals("transcript"u8)) + { + transcript = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioResponseData(id, expiresAt, data, transcript, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AudioResponseData)} does not support writing '{options.Format}' format."); + } + } + + AudioResponseData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioResponseData(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioResponseData)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioResponseData FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioResponseData(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.cs new file mode 100644 index 000000000000..11b58d1feb11 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioResponseData.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Object containing audio response data and its metadata. + public partial class AudioResponseData + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Unique identifier for this audio response. + /// + /// The Unix timestamp (in seconds) for when this audio response + /// will no longer be accessible on the server for use in multi-turn + /// conversations. + /// + /// + /// Base64 encoded audio bytes generated by the model, in the format + /// specified in the request. + /// + /// Transcript of the audio generated by the model. + /// , or is null. + internal AudioResponseData(string id, DateTimeOffset expiresAt, string data, string transcript) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNull(transcript, nameof(transcript)); + + Id = id; + ExpiresAt = expiresAt; + Data = data; + Transcript = transcript; + } + + /// Initializes a new instance of . + /// Unique identifier for this audio response. + /// + /// The Unix timestamp (in seconds) for when this audio response + /// will no longer be accessible on the server for use in multi-turn + /// conversations. + /// + /// + /// Base64 encoded audio bytes generated by the model, in the format + /// specified in the request. + /// + /// Transcript of the audio generated by the model. + /// Keeps track of any properties unknown to the library. + internal AudioResponseData(string id, DateTimeOffset expiresAt, string data, string transcript, IDictionary serializedAdditionalRawData) + { + Id = id; + ExpiresAt = expiresAt; + Data = data; + Transcript = transcript; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioResponseData() + { + } + + /// Unique identifier for this audio response. + public string Id { get; } + /// + /// The Unix timestamp (in seconds) for when this audio response + /// will no longer be accessible on the server for use in multi-turn + /// conversations. + /// + public DateTimeOffset ExpiresAt { get; } + /// + /// Base64 encoded audio bytes generated by the model, in the format + /// specified in the request. + /// + public string Data { get; } + /// Transcript of the audio generated by the model. + public string Transcript { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTaskLabel.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTaskLabel.cs new file mode 100644 index 000000000000..e4669cce267d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTaskLabel.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines the possible descriptors for available audio operation responses. + internal readonly partial struct AudioTaskLabel : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTaskLabel(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string TranscribeValue = "transcribe"; + private const string TranslateValue = "translate"; + + /// Accompanying response data resulted from an audio transcription task. + public static AudioTaskLabel Transcribe { get; } = new AudioTaskLabel(TranscribeValue); + /// Accompanying response data resulted from an audio translation task. + public static AudioTaskLabel Translate { get; } = new AudioTaskLabel(TranslateValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTaskLabel left, AudioTaskLabel right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTaskLabel left, AudioTaskLabel right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTaskLabel(string value) => new AudioTaskLabel(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTaskLabel other && Equals(other); + /// + public bool Equals(AudioTaskLabel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.Serialization.cs new file mode 100644 index 000000000000..a1e94d5e5640 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.Serialization.cs @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscription : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscription)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + if (Optional.IsDefined(InternalAudioTaskLabel)) + { + writer.WritePropertyName("task"u8); + writer.WriteStringValue(InternalAudioTaskLabel.Value.ToString()); + } + if (Optional.IsDefined(Language)) + { + writer.WritePropertyName("language"u8); + writer.WriteStringValue(Language); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("duration"u8); + writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); + } + if (Optional.IsCollectionDefined(Segments)) + { + writer.WritePropertyName("segments"u8); + writer.WriteStartArray(); + foreach (var item in Segments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(Words)) + { + writer.WritePropertyName("words"u8); + writer.WriteStartArray(); + foreach (var item in Words) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioTranscription IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscription)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscription(document.RootElement, options); + } + + internal static AudioTranscription DeserializeAudioTranscription(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + AudioTaskLabel? task = default; + string language = default; + TimeSpan? duration = default; + IReadOnlyList segments = default; + IReadOnlyList words = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("task"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + task = new AudioTaskLabel(property.Value.GetString()); + continue; + } + if (property.NameEquals("language"u8)) + { + language = property.Value.GetString(); + continue; + } + if (property.NameEquals("duration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + duration = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("segments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AudioTranscriptionSegment.DeserializeAudioTranscriptionSegment(item, options)); + } + segments = array; + continue; + } + if (property.NameEquals("words"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AudioTranscriptionWord.DeserializeAudioTranscriptionWord(item, options)); + } + words = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscription( + text, + task, + language, + duration, + segments ?? new ChangeTrackingList(), + words ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AudioTranscription)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscription IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscription(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscription)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscription FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscription(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.cs new file mode 100644 index 000000000000..af332f94ac50 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscription.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Result information for an operation that transcribed spoken audio into written text. + public partial class AudioTranscription + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The transcribed text for the provided audio data. + /// is null. + internal AudioTranscription(string text) + { + Argument.AssertNotNull(text, nameof(text)); + + Text = text; + Segments = new ChangeTrackingList(); + Words = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The transcribed text for the provided audio data. + /// The label that describes which operation type generated the accompanying response data. + /// + /// The spoken language that was detected in the transcribed audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + /// The total duration of the audio processed to produce accompanying transcription information. + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + /// A collection of information about the timing of each processed word. + /// Keeps track of any properties unknown to the library. + internal AudioTranscription(string text, AudioTaskLabel? internalAudioTaskLabel, string language, TimeSpan? duration, IReadOnlyList segments, IReadOnlyList words, IDictionary serializedAdditionalRawData) + { + Text = text; + InternalAudioTaskLabel = internalAudioTaskLabel; + Language = language; + Duration = duration; + Segments = segments; + Words = words; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranscription() + { + } + + /// The transcribed text for the provided audio data. + public string Text { get; } + /// The label that describes which operation type generated the accompanying response data. + public AudioTaskLabel? InternalAudioTaskLabel { get; } + /// + /// The spoken language that was detected in the transcribed audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + public string Language { get; } + /// The total duration of the audio processed to produce accompanying transcription information. + public TimeSpan? Duration { get; } + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + public IReadOnlyList Segments { get; } + /// A collection of information about the timing of each processed word. + public IReadOnlyList Words { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionFormat.cs new file mode 100644 index 000000000000..fc8228609c41 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionFormat.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines available options for the underlying response format of output transcription information. + public readonly partial struct AudioTranscriptionFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTranscriptionFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "json"; + private const string VerboseValue = "verbose_json"; + private const string InternalPlainTextValue = "text"; + private const string SrtValue = "srt"; + private const string VttValue = "vtt"; + + /// Use a response body that is a JSON object containing a single 'text' field for the transcription. + public static AudioTranscriptionFormat Simple { get; } = new AudioTranscriptionFormat(SimpleValue); + /// + /// Use a response body that is a JSON object containing transcription text along with timing, segments, and other + /// metadata. + /// + public static AudioTranscriptionFormat Verbose { get; } = new AudioTranscriptionFormat(VerboseValue); + /// Use a response body that is plain text containing the raw, unannotated transcription. + public static AudioTranscriptionFormat InternalPlainText { get; } = new AudioTranscriptionFormat(InternalPlainTextValue); + /// Use a response body that is plain text in SubRip (SRT) format that also includes timing information. + public static AudioTranscriptionFormat Srt { get; } = new AudioTranscriptionFormat(SrtValue); + /// Use a response body that is plain text in Web Video Text Tracks (VTT) format that also includes timing information. + public static AudioTranscriptionFormat Vtt { get; } = new AudioTranscriptionFormat(VttValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTranscriptionFormat left, AudioTranscriptionFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTranscriptionFormat left, AudioTranscriptionFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTranscriptionFormat(string value) => new AudioTranscriptionFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTranscriptionFormat other && Equals(other); + /// + public bool Equals(AudioTranscriptionFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.Serialization.cs new file mode 100644 index 000000000000..bb0d57649ff7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.Serialization.cs @@ -0,0 +1,313 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscriptionOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(AudioData)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(AudioData), ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Filename)) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Language)) + { + writer.WritePropertyName("language"u8); + writer.WriteStringValue(Language); + } + if (Optional.IsDefined(Prompt)) + { + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsCollectionDefined(TimestampGranularities)) + { + writer.WritePropertyName("timestamp_granularities"u8); + writer.WriteStartArray(); + foreach (var item in TimestampGranularities) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioTranscriptionOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscriptionOptions(document.RootElement, options); + } + + internal static AudioTranscriptionOptions DeserializeAudioTranscriptionOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream file = default; + string filename = default; + AudioTranscriptionFormat? responseFormat = default; + string language = default; + string prompt = default; + float? temperature = default; + IList timestampGranularities = default; + string model = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file"u8)) + { + file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new AudioTranscriptionFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("language"u8)) + { + language = property.Value.GetString(); + continue; + } + if (property.NameEquals("prompt"u8)) + { + prompt = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("timestamp_granularities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new AudioTranscriptionTimestampGranularity(item.GetString())); + } + timestampGranularities = array; + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscriptionOptions( + file, + filename, + responseFormat, + language, + prompt, + temperature, + timestampGranularities ?? new ChangeTrackingList(), + model, + serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(AudioData, "file", "file", "application/octet-stream"); + if (Optional.IsDefined(Filename)) + { + content.Add(Filename, "filename"); + } + if (Optional.IsDefined(ResponseFormat)) + { + content.Add(ResponseFormat.Value.ToString(), "response_format"); + } + if (Optional.IsDefined(Language)) + { + content.Add(Language, "language"); + } + if (Optional.IsDefined(Prompt)) + { + content.Add(Prompt, "prompt"); + } + if (Optional.IsDefined(Temperature)) + { + content.Add(Temperature.Value, "temperature"); + } + if (Optional.IsCollectionDefined(TimestampGranularities)) + { + foreach (AudioTranscriptionTimestampGranularity item in TimestampGranularities) + { + content.Add(item.ToString(), "timestamp_granularities"); + } + } + if (Optional.IsDefined(DeploymentName)) + { + content.Add(DeploymentName, "model"); + } + return content; + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscriptionOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscriptionOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscriptionOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscriptionOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscriptionOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.cs new file mode 100644 index 000000000000..e4c0a5294401 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionOptions.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The configuration information for an audio transcription request. + public partial class AudioTranscriptionOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// 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. + /// + /// is null. + public AudioTranscriptionOptions(Stream audioData) + { + Argument.AssertNotNull(audioData, nameof(audioData)); + + AudioData = audioData; + TimestampGranularities = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the transcription response data, which will influence the content and detail of the result. + /// + /// The primary spoken language of the audio data to be transcribed, supplied as a two-letter ISO-639-1 language code + /// such as 'en' or 'fr'. + /// Providing this known input language is optional but may improve the accuracy and/or latency of transcription. + /// + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// 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. + /// + /// + /// The timestamp granularities to populate for this transcription. + /// `response_format` must be set `verbose_json` to use timestamp granularities. + /// Either or both of these options are supported: `word`, or `segment`. + /// Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + /// + /// The model to use for this transcription request. + /// Keeps track of any properties unknown to the library. + internal AudioTranscriptionOptions(Stream audioData, string filename, AudioTranscriptionFormat? responseFormat, string language, string prompt, float? temperature, IList timestampGranularities, string deploymentName, IDictionary serializedAdditionalRawData) + { + AudioData = audioData; + Filename = filename; + ResponseFormat = responseFormat; + Language = language; + Prompt = prompt; + Temperature = temperature; + TimestampGranularities = timestampGranularities; + DeploymentName = deploymentName; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal 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. + /// + public Stream AudioData { get; } + /// The optional filename or descriptive identifier to associate with with the audio data. + public string Filename { get; set; } + /// The requested format of the transcription response data, which will influence the content and detail of the result. + public AudioTranscriptionFormat? ResponseFormat { get; set; } + /// + /// The primary spoken language of the audio data to be transcribed, supplied as a two-letter ISO-639-1 language code + /// such as 'en' or 'fr'. + /// Providing this known input language is optional but may improve the accuracy and/or latency of transcription. + /// + public string Language { get; set; } + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + public string Prompt { get; set; } + /// + /// 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. + /// + public float? Temperature { get; set; } + /// + /// The timestamp granularities to populate for this transcription. + /// `response_format` must be set `verbose_json` to use timestamp granularities. + /// Either or both of these options are supported: `word`, or `segment`. + /// Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. + /// + public IList TimestampGranularities { get; } + /// The model to use for this transcription request. + public string DeploymentName { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.Serialization.cs new file mode 100644 index 000000000000..cdef69b02e69 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.Serialization.cs @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscriptionSegment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscriptionSegment)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteNumberValue(Id); + writer.WritePropertyName("start"u8); + writer.WriteNumberValue(Convert.ToDouble(Start.ToString("s\\.FFF"))); + writer.WritePropertyName("end"u8); + writer.WriteNumberValue(Convert.ToDouble(End.ToString("s\\.FFF"))); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature); + writer.WritePropertyName("avg_logprob"u8); + writer.WriteNumberValue(AverageLogProbability); + writer.WritePropertyName("compression_ratio"u8); + writer.WriteNumberValue(CompressionRatio); + writer.WritePropertyName("no_speech_prob"u8); + writer.WriteNumberValue(NoSpeechProbability); + writer.WritePropertyName("tokens"u8); + writer.WriteStartArray(); + foreach (var item in Tokens) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("seek"u8); + writer.WriteNumberValue(Seek); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioTranscriptionSegment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscriptionSegment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscriptionSegment(document.RootElement, options); + } + + internal static AudioTranscriptionSegment DeserializeAudioTranscriptionSegment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int id = default; + TimeSpan start = default; + TimeSpan end = default; + string text = default; + float temperature = default; + float avgLogprob = default; + float compressionRatio = default; + float noSpeechProb = default; + IReadOnlyList tokens = default; + int seek = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("start"u8)) + { + start = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("end"u8)) + { + end = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("avg_logprob"u8)) + { + avgLogprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("compression_ratio"u8)) + { + compressionRatio = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("no_speech_prob"u8)) + { + noSpeechProb = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("tokens"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + tokens = array; + continue; + } + if (property.NameEquals("seek"u8)) + { + seek = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscriptionSegment( + id, + start, + end, + text, + temperature, + avgLogprob, + compressionRatio, + noSpeechProb, + tokens, + seek, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AudioTranscriptionSegment)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscriptionSegment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscriptionSegment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscriptionSegment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscriptionSegment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscriptionSegment(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.cs new file mode 100644 index 000000000000..e1dd9c8fad59 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionSegment.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// 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 + /// necessarily sentences. + /// + public partial class AudioTranscriptionSegment + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The 0-based index of this segment within a transcription. + /// The time at which this segment started relative to the beginning of the transcribed audio. + /// The time at which this segment ended relative to the beginning of the transcribed audio. + /// The transcribed text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the transcribed text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// or is null. + internal AudioTranscriptionSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IEnumerable tokens, int seek) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(tokens, nameof(tokens)); + + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens.ToList(); + Seek = seek; + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a transcription. + /// The time at which this segment started relative to the beginning of the transcribed audio. + /// The time at which this segment ended relative to the beginning of the transcribed audio. + /// The transcribed text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the transcribed text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// Keeps track of any properties unknown to the library. + internal AudioTranscriptionSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IReadOnlyList tokens, int seek, IDictionary serializedAdditionalRawData) + { + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens; + Seek = seek; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranscriptionSegment() + { + } + + /// The 0-based index of this segment within a transcription. + public int Id { get; } + /// The time at which this segment started relative to the beginning of the transcribed audio. + public TimeSpan Start { get; } + /// The time at which this segment ended relative to the beginning of the transcribed audio. + public TimeSpan End { get; } + /// The transcribed text that was part of this audio segment. + public string Text { get; } + /// The temperature score associated with this audio segment. + public float Temperature { get; } + /// The average log probability associated with this audio segment. + public float AverageLogProbability { get; } + /// The compression ratio of this audio segment. + public float CompressionRatio { get; } + /// The probability of no speech detection within this audio segment. + public float NoSpeechProbability { get; } + /// The token IDs matching the transcribed text in this audio segment. + public IReadOnlyList Tokens { get; } + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + public int Seek { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionTimestampGranularity.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionTimestampGranularity.cs new file mode 100644 index 000000000000..b0ae51145060 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionTimestampGranularity.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines the timestamp granularities that can be requested on a verbose transcription response. + public readonly partial struct AudioTranscriptionTimestampGranularity : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTranscriptionTimestampGranularity(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string WordValue = "word"; + private const string SegmentValue = "segment"; + + /// + /// Indicates that responses should include timing information about each transcribed word. Note that generating word + /// timestamp information will incur additional response latency. + /// + public static AudioTranscriptionTimestampGranularity Word { get; } = new AudioTranscriptionTimestampGranularity(WordValue); + /// + /// Indicates that responses should include timing and other information about each transcribed audio segment. Audio + /// segment timestamp information does not incur any additional latency. + /// + public static AudioTranscriptionTimestampGranularity Segment { get; } = new AudioTranscriptionTimestampGranularity(SegmentValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTranscriptionTimestampGranularity left, AudioTranscriptionTimestampGranularity right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTranscriptionTimestampGranularity left, AudioTranscriptionTimestampGranularity right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTranscriptionTimestampGranularity(string value) => new AudioTranscriptionTimestampGranularity(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTranscriptionTimestampGranularity other && Equals(other); + /// + public bool Equals(AudioTranscriptionTimestampGranularity other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.Serialization.cs new file mode 100644 index 000000000000..fad645758a38 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranscriptionWord : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscriptionWord)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("word"u8); + writer.WriteStringValue(Word); + writer.WritePropertyName("start"u8); + writer.WriteNumberValue(Convert.ToDouble(Start.ToString("s\\.FFF"))); + writer.WritePropertyName("end"u8); + writer.WriteNumberValue(Convert.ToDouble(End.ToString("s\\.FFF"))); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioTranscriptionWord IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranscriptionWord)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranscriptionWord(document.RootElement, options); + } + + internal static AudioTranscriptionWord DeserializeAudioTranscriptionWord(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string word = default; + TimeSpan start = default; + TimeSpan end = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("word"u8)) + { + word = property.Value.GetString(); + continue; + } + if (property.NameEquals("start"u8)) + { + start = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("end"u8)) + { + end = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranscriptionWord(word, start, end, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AudioTranscriptionWord)} does not support writing '{options.Format}' format."); + } + } + + AudioTranscriptionWord IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscriptionWord(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranscriptionWord)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranscriptionWord FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranscriptionWord(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.cs new file mode 100644 index 000000000000..9fa92dfadb66 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranscriptionWord.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Extended information about a single transcribed word, as provided on responses when the 'word' timestamp granularity is provided. + public partial class AudioTranscriptionWord + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The textual content of the word. + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + /// is null. + internal AudioTranscriptionWord(string word, TimeSpan start, TimeSpan end) + { + Argument.AssertNotNull(word, nameof(word)); + + Word = word; + Start = start; + End = end; + } + + /// Initializes a new instance of . + /// The textual content of the word. + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + /// Keeps track of any properties unknown to the library. + internal AudioTranscriptionWord(string word, TimeSpan start, TimeSpan end, IDictionary serializedAdditionalRawData) + { + Word = word; + Start = start; + End = end; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranscriptionWord() + { + } + + /// The textual content of the word. + public string Word { get; } + /// The start time of the word relative to the beginning of the audio, expressed in seconds. + public TimeSpan Start { get; } + /// The end time of the word relative to the beginning of the audio, expressed in seconds. + public TimeSpan End { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.Serialization.cs new file mode 100644 index 000000000000..b97c051403e6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.Serialization.cs @@ -0,0 +1,214 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranslation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranslation)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + if (Optional.IsDefined(InternalAudioTaskLabel)) + { + writer.WritePropertyName("task"u8); + writer.WriteStringValue(InternalAudioTaskLabel.Value.ToString()); + } + if (Optional.IsDefined(Language)) + { + writer.WritePropertyName("language"u8); + writer.WriteStringValue(Language); + } + if (Optional.IsDefined(Duration)) + { + writer.WritePropertyName("duration"u8); + writer.WriteNumberValue(Convert.ToDouble(Duration.Value.ToString("s\\.FFF"))); + } + if (Optional.IsCollectionDefined(Segments)) + { + writer.WritePropertyName("segments"u8); + writer.WriteStartArray(); + foreach (var item in Segments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioTranslation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranslation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranslation(document.RootElement, options); + } + + internal static AudioTranslation DeserializeAudioTranslation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + AudioTaskLabel? task = default; + string language = default; + TimeSpan? duration = default; + IReadOnlyList segments = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("task"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + task = new AudioTaskLabel(property.Value.GetString()); + continue; + } + if (property.NameEquals("language"u8)) + { + language = property.Value.GetString(); + continue; + } + if (property.NameEquals("duration"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + duration = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("segments"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AudioTranslationSegment.DeserializeAudioTranslationSegment(item, options)); + } + segments = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranslation( + text, + task, + language, + duration, + segments ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AudioTranslation)} does not support writing '{options.Format}' format."); + } + } + + AudioTranslation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranslation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranslation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranslation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranslation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.cs new file mode 100644 index 000000000000..476c481e3824 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslation.cs @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Result information for an operation that translated spoken audio into written text. + public partial class AudioTranslation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The translated text for the provided audio data. + /// is null. + internal AudioTranslation(string text) + { + Argument.AssertNotNull(text, nameof(text)); + + Text = text; + Segments = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The translated text for the provided audio data. + /// The label that describes which operation type generated the accompanying response data. + /// + /// The spoken language that was detected in the translated audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + /// The total duration of the audio processed to produce accompanying translation information. + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + /// Keeps track of any properties unknown to the library. + internal AudioTranslation(string text, AudioTaskLabel? internalAudioTaskLabel, string language, TimeSpan? duration, IReadOnlyList segments, IDictionary serializedAdditionalRawData) + { + Text = text; + InternalAudioTaskLabel = internalAudioTaskLabel; + Language = language; + Duration = duration; + Segments = segments; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranslation() + { + } + + /// The translated text for the provided audio data. + public string Text { get; } + /// The label that describes which operation type generated the accompanying response data. + public AudioTaskLabel? InternalAudioTaskLabel { get; } + /// + /// The spoken language that was detected in the translated audio data. + /// This is expressed as a two-letter ISO-639-1 language code like 'en' or 'fr'. + /// + public string Language { get; } + /// The total duration of the audio processed to produce accompanying translation information. + public TimeSpan? Duration { get; } + /// A collection of information about the timing, probabilities, and other detail of each processed audio segment. + public IReadOnlyList Segments { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationFormat.cs new file mode 100644 index 000000000000..0c8068cb6afe --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationFormat.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Defines available options for the underlying response format of output translation information. + public readonly partial struct AudioTranslationFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AudioTranslationFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "json"; + private const string VerboseValue = "verbose_json"; + private const string InternalPlainTextValue = "text"; + private const string SrtValue = "srt"; + private const string VttValue = "vtt"; + + /// Use a response body that is a JSON object containing a single 'text' field for the translation. + public static AudioTranslationFormat Simple { get; } = new AudioTranslationFormat(SimpleValue); + /// + /// Use a response body that is a JSON object containing translation text along with timing, segments, and other + /// metadata. + /// + public static AudioTranslationFormat Verbose { get; } = new AudioTranslationFormat(VerboseValue); + /// Use a response body that is plain text containing the raw, unannotated translation. + public static AudioTranslationFormat InternalPlainText { get; } = new AudioTranslationFormat(InternalPlainTextValue); + /// Use a response body that is plain text in SubRip (SRT) format that also includes timing information. + public static AudioTranslationFormat Srt { get; } = new AudioTranslationFormat(SrtValue); + /// Use a response body that is plain text in Web Video Text Tracks (VTT) format that also includes timing information. + public static AudioTranslationFormat Vtt { get; } = new AudioTranslationFormat(VttValue); + /// Determines if two values are the same. + public static bool operator ==(AudioTranslationFormat left, AudioTranslationFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AudioTranslationFormat left, AudioTranslationFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AudioTranslationFormat(string value) => new AudioTranslationFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AudioTranslationFormat other && Equals(other); + /// + public bool Equals(AudioTranslationFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.Serialization.cs new file mode 100644 index 000000000000..c8c33bd61eea --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.Serialization.cs @@ -0,0 +1,264 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranslationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("file"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(global::System.BinaryData.FromStream(AudioData)); +#else + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(AudioData), ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Filename)) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Prompt)) + { + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioTranslationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranslationOptions(document.RootElement, options); + } + + internal static AudioTranslationOptions DeserializeAudioTranslationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Stream file = default; + string filename = default; + AudioTranslationFormat? responseFormat = default; + string prompt = default; + float? temperature = default; + string model = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("file"u8)) + { + file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new AudioTranslationFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("prompt"u8)) + { + prompt = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranslationOptions( + file, + filename, + responseFormat, + prompt, + temperature, + model, + serializedAdditionalRawData); + } + + private BinaryData SerializeMultipart(ModelReaderWriterOptions options) + { + using MultipartFormDataRequestContent content = ToMultipartRequestContent(); + using MemoryStream stream = new MemoryStream(); + content.WriteTo(stream); + if (stream.Position > int.MaxValue) + { + return BinaryData.FromStream(stream); + } + else + { + return new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position)); + } + } + + internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() + { + MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); + content.Add(AudioData, "file", "file", "application/octet-stream"); + if (Optional.IsDefined(Filename)) + { + content.Add(Filename, "filename"); + } + if (Optional.IsDefined(ResponseFormat)) + { + content.Add(ResponseFormat.Value.ToString(), "response_format"); + } + if (Optional.IsDefined(Prompt)) + { + content.Add(Prompt, "prompt"); + } + if (Optional.IsDefined(Temperature)) + { + content.Add(Temperature.Value, "temperature"); + } + if (Optional.IsDefined(DeploymentName)) + { + content.Add(DeploymentName, "model"); + } + return content; + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + case "MFD": + return SerializeMultipart(options); + default: + throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support writing '{options.Format}' format."); + } + } + + AudioTranslationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranslationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranslationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranslationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranslationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.cs new file mode 100644 index 000000000000..63936f35c61c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationOptions.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The configuration information for an audio translation request. + public partial class AudioTranslationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// 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. + /// + /// is null. + public AudioTranslationOptions(Stream audioData) + { + Argument.AssertNotNull(audioData, nameof(audioData)); + + AudioData = audioData; + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// The optional filename or descriptive identifier to associate with with the audio data. + /// The requested format of the translation response data, which will influence the content and detail of the result. + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + /// + /// 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. + /// + /// The model to use for this translation request. + /// Keeps track of any properties unknown to the library. + internal AudioTranslationOptions(Stream audioData, string filename, AudioTranslationFormat? responseFormat, string prompt, float? temperature, string deploymentName, IDictionary serializedAdditionalRawData) + { + AudioData = audioData; + Filename = filename; + ResponseFormat = responseFormat; + Prompt = prompt; + Temperature = temperature; + DeploymentName = deploymentName; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal 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. + /// + public Stream AudioData { get; } + /// The optional filename or descriptive identifier to associate with with the audio data. + public string Filename { get; set; } + /// The requested format of the translation response data, which will influence the content and detail of the result. + public AudioTranslationFormat? ResponseFormat { get; set; } + /// + /// An optional hint to guide the model's style or continue from a prior audio segment. The written language of the + /// prompt should match the primary spoken language of the audio data. + /// + public string Prompt { get; set; } + /// + /// 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. + /// + public float? Temperature { get; set; } + /// The model to use for this translation request. + public string DeploymentName { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.Serialization.cs new file mode 100644 index 000000000000..559f16183763 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.Serialization.cs @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AudioTranslationSegment : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranslationSegment)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteNumberValue(Id); + writer.WritePropertyName("start"u8); + writer.WriteNumberValue(Convert.ToDouble(Start.ToString("s\\.FFF"))); + writer.WritePropertyName("end"u8); + writer.WriteNumberValue(Convert.ToDouble(End.ToString("s\\.FFF"))); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature); + writer.WritePropertyName("avg_logprob"u8); + writer.WriteNumberValue(AverageLogProbability); + writer.WritePropertyName("compression_ratio"u8); + writer.WriteNumberValue(CompressionRatio); + writer.WritePropertyName("no_speech_prob"u8); + writer.WriteNumberValue(NoSpeechProbability); + writer.WritePropertyName("tokens"u8); + writer.WriteStartArray(); + foreach (var item in Tokens) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("seek"u8); + writer.WriteNumberValue(Seek); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AudioTranslationSegment IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AudioTranslationSegment)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAudioTranslationSegment(document.RootElement, options); + } + + internal static AudioTranslationSegment DeserializeAudioTranslationSegment(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int id = default; + TimeSpan start = default; + TimeSpan end = default; + string text = default; + float temperature = default; + float avgLogprob = default; + float compressionRatio = default; + float noSpeechProb = default; + IReadOnlyList tokens = default; + int seek = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("start"u8)) + { + start = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("end"u8)) + { + end = TimeSpan.FromSeconds(property.Value.GetDouble()); + continue; + } + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("avg_logprob"u8)) + { + avgLogprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("compression_ratio"u8)) + { + compressionRatio = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("no_speech_prob"u8)) + { + noSpeechProb = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("tokens"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + tokens = array; + continue; + } + if (property.NameEquals("seek"u8)) + { + seek = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AudioTranslationSegment( + id, + start, + end, + text, + temperature, + avgLogprob, + compressionRatio, + noSpeechProb, + tokens, + seek, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AudioTranslationSegment)} does not support writing '{options.Format}' format."); + } + } + + AudioTranslationSegment IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranslationSegment(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AudioTranslationSegment)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AudioTranslationSegment FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAudioTranslationSegment(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.cs new file mode 100644 index 000000000000..4eba8ec055ae --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AudioTranslationSegment.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// Extended information about a single segment of translated audio data. + /// Segments generally represent roughly 5-10 seconds of speech. Segment boundaries typically occur between words but not + /// necessarily sentences. + /// + public partial class AudioTranslationSegment + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The 0-based index of this segment within a translation. + /// The time at which this segment started relative to the beginning of the translated audio. + /// The time at which this segment ended relative to the beginning of the translated audio. + /// The translated text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the translated text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// or is null. + internal AudioTranslationSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IEnumerable tokens, int seek) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(tokens, nameof(tokens)); + + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens.ToList(); + Seek = seek; + } + + /// Initializes a new instance of . + /// The 0-based index of this segment within a translation. + /// The time at which this segment started relative to the beginning of the translated audio. + /// The time at which this segment ended relative to the beginning of the translated audio. + /// The translated text that was part of this audio segment. + /// The temperature score associated with this audio segment. + /// The average log probability associated with this audio segment. + /// The compression ratio of this audio segment. + /// The probability of no speech detection within this audio segment. + /// The token IDs matching the translated text in this audio segment. + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + /// Keeps track of any properties unknown to the library. + internal AudioTranslationSegment(int id, TimeSpan start, TimeSpan end, string text, float temperature, float averageLogProbability, float compressionRatio, float noSpeechProbability, IReadOnlyList tokens, int seek, IDictionary serializedAdditionalRawData) + { + Id = id; + Start = start; + End = end; + Text = text; + Temperature = temperature; + AverageLogProbability = averageLogProbability; + CompressionRatio = compressionRatio; + NoSpeechProbability = noSpeechProbability; + Tokens = tokens; + Seek = seek; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AudioTranslationSegment() + { + } + + /// The 0-based index of this segment within a translation. + public int Id { get; } + /// The time at which this segment started relative to the beginning of the translated audio. + public TimeSpan Start { get; } + /// The time at which this segment ended relative to the beginning of the translated audio. + public TimeSpan End { get; } + /// The translated text that was part of this audio segment. + public string Text { get; } + /// The temperature score associated with this audio segment. + public float Temperature { get; } + /// The average log probability associated with this audio segment. + public float AverageLogProbability { get; } + /// The compression ratio of this audio segment. + public float CompressionRatio { get; } + /// The probability of no speech detection within this audio segment. + public float NoSpeechProbability { get; } + /// The token IDs matching the translated text in this audio segment. + public IReadOnlyList Tokens { get; } + /// + /// The seek position associated with the processing of this audio segment. + /// Seek positions are expressed as hundredths of seconds. + /// The model may process several segments from a single seek position, so while the seek position will never represent + /// a later time than the segment's start, the segment's start may represent a significantly later time than the + /// segment's associated seek position. + /// + public int Seek { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.Serialization.cs new file mode 100644 index 000000000000..41f6bb26b151 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.Serialization.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatEnhancementConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatEnhancementConfiguration)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Grounding)) + { + writer.WritePropertyName("grounding"u8); + writer.WriteObjectValue(Grounding, options); + } + if (Optional.IsDefined(Ocr)) + { + writer.WritePropertyName("ocr"u8); + writer.WriteObjectValue(Ocr, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatEnhancementConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatEnhancementConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatEnhancementConfiguration(document.RootElement, options); + } + + internal static AzureChatEnhancementConfiguration DeserializeAzureChatEnhancementConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureChatGroundingEnhancementConfiguration grounding = default; + AzureChatOCREnhancementConfiguration ocr = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("grounding"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + grounding = AzureChatGroundingEnhancementConfiguration.DeserializeAzureChatGroundingEnhancementConfiguration(property.Value, options); + continue; + } + if (property.NameEquals("ocr"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + ocr = AzureChatOCREnhancementConfiguration.DeserializeAzureChatOCREnhancementConfiguration(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatEnhancementConfiguration(grounding, ocr, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatEnhancementConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatEnhancementConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatEnhancementConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatEnhancementConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatEnhancementConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatEnhancementConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.cs new file mode 100644 index 000000000000..9abaf36c33a7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancementConfiguration.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the available Azure OpenAI enhancement configurations. + public partial class AzureChatEnhancementConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public AzureChatEnhancementConfiguration() + { + } + + /// Initializes a new instance of . + /// A representation of the available options for the Azure OpenAI grounding enhancement. + /// A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. + /// Keeps track of any properties unknown to the library. + internal AzureChatEnhancementConfiguration(AzureChatGroundingEnhancementConfiguration grounding, AzureChatOCREnhancementConfiguration ocr, IDictionary serializedAdditionalRawData) + { + Grounding = grounding; + Ocr = ocr; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// A representation of the available options for the Azure OpenAI grounding enhancement. + public AzureChatGroundingEnhancementConfiguration Grounding { get; set; } + /// A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. + public AzureChatOCREnhancementConfiguration Ocr { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.Serialization.cs new file mode 100644 index 000000000000..4a970b653d46 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatEnhancements : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatEnhancements)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Grounding)) + { + writer.WritePropertyName("grounding"u8); + writer.WriteObjectValue(Grounding, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatEnhancements IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatEnhancements)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatEnhancements(document.RootElement, options); + } + + internal static AzureChatEnhancements DeserializeAzureChatEnhancements(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureGroundingEnhancement grounding = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("grounding"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + grounding = AzureGroundingEnhancement.DeserializeAzureGroundingEnhancement(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatEnhancements(grounding, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatEnhancements)} does not support writing '{options.Format}' format."); + } + } + + AzureChatEnhancements IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatEnhancements(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatEnhancements)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatEnhancements FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatEnhancements(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.cs new file mode 100644 index 000000000000..113d9a88ea0a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatEnhancements.cs @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// Represents the output results of Azure enhancements to chat completions, as configured via the matching input provided + /// in the request. + /// + public partial class AzureChatEnhancements + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal AzureChatEnhancements() + { + } + + /// Initializes a new instance of . + /// The grounding enhancement that returns the bounding box of the objects detected in the image. + /// Keeps track of any properties unknown to the library. + internal AzureChatEnhancements(AzureGroundingEnhancement grounding, IDictionary serializedAdditionalRawData) + { + Grounding = grounding; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The grounding enhancement that returns the bounding box of the objects detected in the image. + public AzureGroundingEnhancement Grounding { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..29a57c17f438 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownAzureChatExtensionConfiguration))] + public partial class AzureChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatExtensionConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + + internal static AzureChatExtensionConfiguration DeserializeAzureChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "azure_cosmos_db": return AzureCosmosDBChatExtensionConfiguration.DeserializeAzureCosmosDBChatExtensionConfiguration(element, options); + case "azure_search": return AzureSearchChatExtensionConfiguration.DeserializeAzureSearchChatExtensionConfiguration(element, options); + case "elasticsearch": return ElasticsearchChatExtensionConfiguration.DeserializeElasticsearchChatExtensionConfiguration(element, options); + case "mongo_db": return MongoDBChatExtensionConfiguration.DeserializeMongoDBChatExtensionConfiguration(element, options); + case "pinecone": return PineconeChatExtensionConfiguration.DeserializePineconeChatExtensionConfiguration(element, options); + } + } + return UnknownAzureChatExtensionConfiguration.DeserializeUnknownAzureChatExtensionConfiguration(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.cs new file mode 100644 index 000000000000..689f1809d2b8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionConfiguration.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public abstract partial class AzureChatExtensionConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected AzureChatExtensionConfiguration() + { + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + internal AzureChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + internal AzureChatExtensionType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.Serialization.cs new file mode 100644 index 000000000000..d513dc0015ca --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.Serialization.cs @@ -0,0 +1,208 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatExtensionDataSourceResponseCitation : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + if (Optional.IsDefined(Title)) + { + writer.WritePropertyName("title"u8); + writer.WriteStringValue(Title); + } + if (Optional.IsDefined(Url)) + { + writer.WritePropertyName("url"u8); + writer.WriteStringValue(Url); + } + if (Optional.IsDefined(Filepath)) + { + writer.WritePropertyName("filepath"u8); + writer.WriteStringValue(Filepath); + } + if (Optional.IsDefined(ChunkId)) + { + writer.WritePropertyName("chunk_id"u8); + writer.WriteStringValue(ChunkId); + } + if (Optional.IsDefined(RerankScore)) + { + writer.WritePropertyName("rerank_score"u8); + writer.WriteNumberValue(RerankScore.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatExtensionDataSourceResponseCitation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionDataSourceResponseCitation(document.RootElement, options); + } + + internal static AzureChatExtensionDataSourceResponseCitation DeserializeAzureChatExtensionDataSourceResponseCitation(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string content = default; + string title = default; + string url = default; + string filepath = default; + string chunkId = default; + double? rerankScore = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("title"u8)) + { + title = property.Value.GetString(); + continue; + } + if (property.NameEquals("url"u8)) + { + url = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath"u8)) + { + filepath = property.Value.GetString(); + continue; + } + if (property.NameEquals("chunk_id"u8)) + { + chunkId = property.Value.GetString(); + continue; + } + if (property.NameEquals("rerank_score"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + rerankScore = property.Value.GetDouble(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatExtensionDataSourceResponseCitation( + content, + title, + url, + filepath, + chunkId, + rerankScore, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionDataSourceResponseCitation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionDataSourceResponseCitation(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionDataSourceResponseCitation)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatExtensionDataSourceResponseCitation FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionDataSourceResponseCitation(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.cs new file mode 100644 index 000000000000..b07ff2f62a95 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionDataSourceResponseCitation.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A single instance of 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. + /// + public partial class AzureChatExtensionDataSourceResponseCitation + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The content of the citation. + /// is null. + internal AzureChatExtensionDataSourceResponseCitation(string content) + { + Argument.AssertNotNull(content, nameof(content)); + + Content = content; + } + + /// Initializes a new instance of . + /// The content of the citation. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. + /// Keeps track of any properties unknown to the library. + internal AzureChatExtensionDataSourceResponseCitation(string content, string title, string url, string filepath, string chunkId, double? rerankScore, IDictionary serializedAdditionalRawData) + { + Content = content; + Title = title; + Url = url; + Filepath = filepath; + ChunkId = chunkId; + RerankScore = rerankScore; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureChatExtensionDataSourceResponseCitation() + { + } + + /// The content of the citation. + public string Content { get; } + /// The title of the citation. + public string Title { get; } + /// The URL of the citation. + public string Url { get; } + /// The file path of the citation. + public string Filepath { get; } + /// The chunk ID of the citation. + public string ChunkId { get; } + /// The rerank score of the retrieved document. + public double? RerankScore { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.Serialization.cs new file mode 100644 index 000000000000..97679b72fb36 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.Serialization.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; + +namespace Azure.AI.OpenAI +{ + internal static partial class AzureChatExtensionRetrieveDocumentFilterReasonExtensions + { + public static string ToSerialString(this AzureChatExtensionRetrieveDocumentFilterReason value) => value switch + { + AzureChatExtensionRetrieveDocumentFilterReason.Score => "score", + AzureChatExtensionRetrieveDocumentFilterReason.Rerank => "rerank", + _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown AzureChatExtensionRetrieveDocumentFilterReason value.") + }; + + public static AzureChatExtensionRetrieveDocumentFilterReason ToAzureChatExtensionRetrieveDocumentFilterReason(this string value) + { + if (StringComparer.OrdinalIgnoreCase.Equals(value, "score")) return AzureChatExtensionRetrieveDocumentFilterReason.Score; + if (StringComparer.OrdinalIgnoreCase.Equals(value, "rerank")) return AzureChatExtensionRetrieveDocumentFilterReason.Rerank; + throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown AzureChatExtensionRetrieveDocumentFilterReason value."); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.cs new file mode 100644 index 000000000000..a0ff002c2627 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrieveDocumentFilterReason.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +namespace Azure.AI.OpenAI +{ + /// The reason for filtering the retrieved document. + public enum AzureChatExtensionRetrieveDocumentFilterReason + { + /// The document is filtered by original search score threshold defined by `strictness` configure. + Score, + /// The document is not filtered by original search score threshold, but is filtered by rerank score and `top_n_documents` configure. + Rerank + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.Serialization.cs new file mode 100644 index 000000000000..d136602eb932 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.Serialization.cs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatExtensionRetrievedDocument : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + if (Optional.IsDefined(Title)) + { + writer.WritePropertyName("title"u8); + writer.WriteStringValue(Title); + } + if (Optional.IsDefined(Url)) + { + writer.WritePropertyName("url"u8); + writer.WriteStringValue(Url); + } + if (Optional.IsDefined(Filepath)) + { + writer.WritePropertyName("filepath"u8); + writer.WriteStringValue(Filepath); + } + if (Optional.IsDefined(ChunkId)) + { + writer.WritePropertyName("chunk_id"u8); + writer.WriteStringValue(ChunkId); + } + if (Optional.IsDefined(RerankScore)) + { + writer.WritePropertyName("rerank_score"u8); + writer.WriteNumberValue(RerankScore.Value); + } + writer.WritePropertyName("search_queries"u8); + writer.WriteStartArray(); + foreach (var item in SearchQueries) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("data_source_index"u8); + writer.WriteNumberValue(DataSourceIndex); + if (Optional.IsDefined(OriginalSearchScore)) + { + writer.WritePropertyName("original_search_score"u8); + writer.WriteNumberValue(OriginalSearchScore.Value); + } + if (Optional.IsDefined(FilterReason)) + { + writer.WritePropertyName("filter_reason"u8); + writer.WriteStringValue(FilterReason.Value.ToSerialString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatExtensionRetrievedDocument IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionRetrievedDocument(document.RootElement, options); + } + + internal static AzureChatExtensionRetrievedDocument DeserializeAzureChatExtensionRetrievedDocument(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string content = default; + string title = default; + string url = default; + string filepath = default; + string chunkId = default; + double? rerankScore = default; + IReadOnlyList searchQueries = default; + int dataSourceIndex = default; + double? originalSearchScore = default; + AzureChatExtensionRetrieveDocumentFilterReason? filterReason = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("title"u8)) + { + title = property.Value.GetString(); + continue; + } + if (property.NameEquals("url"u8)) + { + url = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath"u8)) + { + filepath = property.Value.GetString(); + continue; + } + if (property.NameEquals("chunk_id"u8)) + { + chunkId = property.Value.GetString(); + continue; + } + if (property.NameEquals("rerank_score"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + rerankScore = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("search_queries"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + searchQueries = array; + continue; + } + if (property.NameEquals("data_source_index"u8)) + { + dataSourceIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("original_search_score"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + originalSearchScore = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("filter_reason"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + filterReason = property.Value.GetString().ToAzureChatExtensionRetrieveDocumentFilterReason(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatExtensionRetrievedDocument( + content, + title, + url, + filepath, + chunkId, + rerankScore, + searchQueries, + dataSourceIndex, + originalSearchScore, + filterReason, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionRetrievedDocument IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionRetrievedDocument(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionRetrievedDocument)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatExtensionRetrievedDocument FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionRetrievedDocument(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.cs new file mode 100644 index 000000000000..8ee20083b474 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionRetrievedDocument.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The retrieved document. + public partial class AzureChatExtensionRetrievedDocument + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The content of the citation. + /// The search queries used to retrieve the document. + /// The index of the data source. + /// or is null. + internal AzureChatExtensionRetrievedDocument(string content, IEnumerable searchQueries, int dataSourceIndex) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNull(searchQueries, nameof(searchQueries)); + + Content = content; + SearchQueries = searchQueries.ToList(); + DataSourceIndex = dataSourceIndex; + } + + /// Initializes a new instance of . + /// The content of the citation. + /// The title of the citation. + /// The URL of the citation. + /// The file path of the citation. + /// The chunk ID of the citation. + /// The rerank score of the retrieved document. + /// The search queries used to retrieve the document. + /// The index of the data source. + /// The original search score of the retrieved document. + /// + /// Represents the rationale for filtering the document. If the document does not undergo filtering, + /// this field will remain unset. + /// + /// Keeps track of any properties unknown to the library. + internal AzureChatExtensionRetrievedDocument(string content, string title, string url, string filepath, string chunkId, double? rerankScore, IReadOnlyList searchQueries, int dataSourceIndex, double? originalSearchScore, AzureChatExtensionRetrieveDocumentFilterReason? filterReason, IDictionary serializedAdditionalRawData) + { + Content = content; + Title = title; + Url = url; + Filepath = filepath; + ChunkId = chunkId; + RerankScore = rerankScore; + SearchQueries = searchQueries; + DataSourceIndex = dataSourceIndex; + OriginalSearchScore = originalSearchScore; + FilterReason = filterReason; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureChatExtensionRetrievedDocument() + { + } + + /// The content of the citation. + public string Content { get; } + /// The title of the citation. + public string Title { get; } + /// The URL of the citation. + public string Url { get; } + /// The file path of the citation. + public string Filepath { get; } + /// The chunk ID of the citation. + public string ChunkId { get; } + /// The rerank score of the retrieved document. + public double? RerankScore { get; } + /// The search queries used to retrieve the document. + public IReadOnlyList SearchQueries { get; } + /// The index of the data source. + public int DataSourceIndex { get; } + /// The original search score of the retrieved document. + public double? OriginalSearchScore { get; } + /// + /// Represents the rationale for filtering the document. If the document does not undergo filtering, + /// this field will remain unset. + /// + public AzureChatExtensionRetrieveDocumentFilterReason? FilterReason { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionType.cs new file mode 100644 index 000000000000..43ed79a551d4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionType.cs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + internal readonly partial struct AzureChatExtensionType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AzureChatExtensionType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AzureSearchValue = "azure_search"; + private const string AzureCosmosDBValue = "azure_cosmos_db"; + private const string ElasticsearchValue = "elasticsearch"; + private const string PineconeValue = "pinecone"; + private const string MongoDBValue = "mongo_db"; + + /// Represents the use of Azure AI Search as an Azure OpenAI chat extension. + public static AzureChatExtensionType AzureSearch { get; } = new AzureChatExtensionType(AzureSearchValue); + /// Represents the use of Azure Cosmos DB as an Azure OpenAI chat extension. + public static AzureChatExtensionType AzureCosmosDB { get; } = new AzureChatExtensionType(AzureCosmosDBValue); + /// Represents the use of Elasticsearch® index as an Azure OpenAI chat extension. + public static AzureChatExtensionType Elasticsearch { get; } = new AzureChatExtensionType(ElasticsearchValue); + /// Represents the use of Pinecone index as an Azure OpenAI chat extension. + public static AzureChatExtensionType Pinecone { get; } = new AzureChatExtensionType(PineconeValue); + /// Represents the use of a MongoDB chat extension. + public static AzureChatExtensionType MongoDB { get; } = new AzureChatExtensionType(MongoDBValue); + /// Determines if two values are the same. + public static bool operator ==(AzureChatExtensionType left, AzureChatExtensionType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AzureChatExtensionType left, AzureChatExtensionType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AzureChatExtensionType(string value) => new AzureChatExtensionType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AzureChatExtensionType other && Equals(other); + /// + public bool Equals(AzureChatExtensionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.Serialization.cs new file mode 100644 index 000000000000..eb3830177f33 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.Serialization.cs @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatExtensionsMessageContext : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionsMessageContext)} does not support writing '{format}' format."); + } + + if (Optional.IsCollectionDefined(Citations)) + { + writer.WritePropertyName("citations"u8); + writer.WriteStartArray(); + foreach (var item in Citations) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Intent)) + { + writer.WritePropertyName("intent"u8); + writer.WriteStringValue(Intent); + } + if (Optional.IsCollectionDefined(AllRetrievedDocuments)) + { + writer.WritePropertyName("all_retrieved_documents"u8); + writer.WriteStartArray(); + foreach (var item in AllRetrievedDocuments) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatExtensionsMessageContext IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionsMessageContext)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionsMessageContext(document.RootElement, options); + } + + internal static AzureChatExtensionsMessageContext DeserializeAzureChatExtensionsMessageContext(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList citations = default; + string intent = default; + IReadOnlyList allRetrievedDocuments = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("citations"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureChatExtensionDataSourceResponseCitation.DeserializeAzureChatExtensionDataSourceResponseCitation(item, options)); + } + citations = array; + continue; + } + if (property.NameEquals("intent"u8)) + { + intent = property.Value.GetString(); + continue; + } + if (property.NameEquals("all_retrieved_documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureChatExtensionRetrievedDocument.DeserializeAzureChatExtensionRetrievedDocument(item, options)); + } + allRetrievedDocuments = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatExtensionsMessageContext(citations ?? new ChangeTrackingList(), intent, allRetrievedDocuments ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatExtensionsMessageContext)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionsMessageContext IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionsMessageContext(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionsMessageContext)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatExtensionsMessageContext FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionsMessageContext(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.cs new file mode 100644 index 000000000000..0591400215bc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatExtensionsMessageContext.cs @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class AzureChatExtensionsMessageContext + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal AzureChatExtensionsMessageContext() + { + Citations = new ChangeTrackingList(); + AllRetrievedDocuments = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// The contextual information 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. + /// + /// The detected intent from the chat history, used to pass to the next turn to carry over the context. + /// All the retrieved documents. + /// Keeps track of any properties unknown to the library. + internal AzureChatExtensionsMessageContext(IReadOnlyList citations, string intent, IReadOnlyList allRetrievedDocuments, IDictionary serializedAdditionalRawData) + { + Citations = citations; + Intent = intent; + AllRetrievedDocuments = allRetrievedDocuments; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// The contextual information 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. + /// + public IReadOnlyList Citations { get; } + /// The detected intent from the chat history, used to pass to the next turn to carry over the context. + public string Intent { get; } + /// All the retrieved documents. + public IReadOnlyList AllRetrievedDocuments { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.Serialization.cs new file mode 100644 index 000000000000..7486f02effed --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatGroundingEnhancementConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatGroundingEnhancementConfiguration)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatGroundingEnhancementConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatGroundingEnhancementConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatGroundingEnhancementConfiguration(document.RootElement, options); + } + + internal static AzureChatGroundingEnhancementConfiguration DeserializeAzureChatGroundingEnhancementConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatGroundingEnhancementConfiguration(enabled, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatGroundingEnhancementConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatGroundingEnhancementConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatGroundingEnhancementConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatGroundingEnhancementConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatGroundingEnhancementConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatGroundingEnhancementConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.cs new file mode 100644 index 000000000000..8e14c4e438d2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatGroundingEnhancementConfiguration.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the available options for the Azure OpenAI grounding enhancement. + public partial class AzureChatGroundingEnhancementConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + public AzureChatGroundingEnhancementConfiguration(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + /// Keeps track of any properties unknown to the library. + internal AzureChatGroundingEnhancementConfiguration(bool enabled, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureChatGroundingEnhancementConfiguration() + { + } + + /// Specifies whether the enhancement is enabled. + public bool Enabled { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.Serialization.cs new file mode 100644 index 000000000000..9b048f71850c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureChatOCREnhancementConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatOCREnhancementConfiguration)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("enabled"u8); + writer.WriteBooleanValue(Enabled); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureChatOCREnhancementConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatOCREnhancementConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatOCREnhancementConfiguration(document.RootElement, options); + } + + internal static AzureChatOCREnhancementConfiguration DeserializeAzureChatOCREnhancementConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool enabled = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("enabled"u8)) + { + enabled = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureChatOCREnhancementConfiguration(enabled, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatOCREnhancementConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatOCREnhancementConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatOCREnhancementConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatOCREnhancementConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureChatOCREnhancementConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatOCREnhancementConfiguration(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.cs new file mode 100644 index 000000000000..6f3aee5baa5a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureChatOCREnhancementConfiguration.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the available options for the Azure OpenAI optical character recognition (OCR) enhancement. + public partial class AzureChatOCREnhancementConfiguration + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + public AzureChatOCREnhancementConfiguration(bool enabled) + { + Enabled = enabled; + } + + /// Initializes a new instance of . + /// Specifies whether the enhancement is enabled. + /// Keeps track of any properties unknown to the library. + internal AzureChatOCREnhancementConfiguration(bool enabled, IDictionary serializedAdditionalRawData) + { + Enabled = enabled; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureChatOCREnhancementConfiguration() + { + } + + /// Specifies whether the enhancement is enabled. + public bool Enabled { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..21309309bd4a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureCosmosDBChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + } + + AzureCosmosDBChatExtensionConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureCosmosDBChatExtensionConfiguration(document.RootElement, options); + } + + internal static AzureCosmosDBChatExtensionConfiguration DeserializeAzureCosmosDBChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureCosmosDBChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = AzureCosmosDBChatExtensionParameters.DeserializeAzureCosmosDBChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureCosmosDBChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureCosmosDBChatExtensionConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureCosmosDBChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new AzureCosmosDBChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureCosmosDBChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.cs new file mode 100644 index 000000000000..c3b36d9749ea --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Azure Cosmos DB when using it as an Azure OpenAI chat + /// extension. + /// + public partial class AzureCosmosDBChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + /// is null. + public AzureCosmosDBChatExtensionConfiguration(AzureCosmosDBChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.AzureCosmosDB; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + internal AzureCosmosDBChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, AzureCosmosDBChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal AzureCosmosDBChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Azure OpenAI CosmosDB chat extensions. + public AzureCosmosDBChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.Serialization.cs new file mode 100644 index 000000000000..9c0f96e93090 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.Serialization.cs @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureCosmosDBChatExtensionParameters : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(DocumentCount)) + { + writer.WritePropertyName("top_n_documents"u8); + writer.WriteNumberValue(DocumentCount.Value); + } + if (Optional.IsDefined(ShouldRestrictResultScope)) + { + writer.WritePropertyName("in_scope"u8); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); + } + if (Optional.IsDefined(Strictness)) + { + writer.WritePropertyName("strictness"u8); + writer.WriteNumberValue(Strictness.Value); + } + if (Optional.IsDefined(MaxSearchQueries)) + { + writer.WritePropertyName("max_search_queries"u8); + writer.WriteNumberValue(MaxSearchQueries.Value); + } + if (Optional.IsDefined(AllowPartialResult)) + { + writer.WritePropertyName("allow_partial_result"u8); + writer.WriteBooleanValue(AllowPartialResult.Value); + } + if (Optional.IsCollectionDefined(IncludeContexts)) + { + writer.WritePropertyName("include_contexts"u8); + writer.WriteStartArray(); + foreach (var item in IncludeContexts) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Authentication)) + { + writer.WritePropertyName("authentication"u8); + writer.WriteObjectValue(Authentication, options); + } + writer.WritePropertyName("database_name"u8); + writer.WriteStringValue(DatabaseName); + writer.WritePropertyName("container_name"u8); + writer.WriteStringValue(ContainerName); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldMappingOptions, options); + writer.WritePropertyName("embedding_dependency"u8); + writer.WriteObjectValue(EmbeddingDependency, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureCosmosDBChatExtensionParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureCosmosDBChatExtensionParameters(document.RootElement, options); + } + + internal static AzureCosmosDBChatExtensionParameters DeserializeAzureCosmosDBChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? topNDocuments = default; + bool? inScope = default; + int? strictness = default; + int? maxSearchQueries = default; + bool? allowPartialResult = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; + string databaseName = default; + string containerName = default; + string indexName = default; + AzureCosmosDBFieldMappingOptions fieldsMapping = default; + OnYourDataVectorizationSource embeddingDependency = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("top_n_documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topNDocuments = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("in_scope"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inScope = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("strictness"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + strictness = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_search_queries"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxSearchQueries = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("allow_partial_result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + allowPartialResult = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("include_contexts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new OnYourDataContextProperty(item.GetString())); + } + includeContexts = array; + continue; + } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); + continue; + } + if (property.NameEquals("database_name"u8)) + { + databaseName = property.Value.GetString(); + continue; + } + if (property.NameEquals("container_name"u8)) + { + containerName = property.Value.GetString(); + continue; + } + if (property.NameEquals("index_name"u8)) + { + indexName = property.Value.GetString(); + continue; + } + if (property.NameEquals("fields_mapping"u8)) + { + fieldsMapping = AzureCosmosDBFieldMappingOptions.DeserializeAzureCosmosDBFieldMappingOptions(property.Value, options); + continue; + } + if (property.NameEquals("embedding_dependency"u8)) + { + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureCosmosDBChatExtensionParameters( + topNDocuments, + inScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts ?? new ChangeTrackingList(), + authentication, + databaseName, + containerName, + indexName, + fieldsMapping, + embeddingDependency, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support writing '{options.Format}' format."); + } + } + + AzureCosmosDBChatExtensionParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureCosmosDBChatExtensionParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureCosmosDBChatExtensionParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureCosmosDBChatExtensionParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureCosmosDBChatExtensionParameters(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.cs new file mode 100644 index 000000000000..af4079791b60 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBChatExtensionParameters.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// Parameters to use when configuring Azure OpenAI On Your Data chat extensions when using Azure Cosmos DB for + /// MongoDB vCore. The supported authentication type is ConnectionString. + /// + public partial class AzureCosmosDBChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The MongoDB vCore database name to use with Azure Cosmos DB. + /// The name of the Azure Cosmos DB resource container. + /// The MongoDB vCore index name to use with Azure Cosmos DB. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// , , , or is null. + public AzureCosmosDBChatExtensionParameters(string databaseName, string containerName, string indexName, AzureCosmosDBFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency) + { + Argument.AssertNotNull(databaseName, nameof(databaseName)); + Argument.AssertNotNull(containerName, nameof(containerName)); + Argument.AssertNotNull(indexName, nameof(indexName)); + Argument.AssertNotNull(fieldMappingOptions, nameof(fieldMappingOptions)); + Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); + + IncludeContexts = new ChangeTrackingList(); + DatabaseName = databaseName; + ContainerName = containerName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The MongoDB vCore database name to use with Azure Cosmos DB. + /// The name of the Azure Cosmos DB resource container. + /// The MongoDB vCore index name to use with Azure Cosmos DB. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal AzureCosmosDBChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, string databaseName, string containerName, string indexName, AzureCosmosDBFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + DatabaseName = databaseName; + ContainerName = containerName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureCosmosDBChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The MongoDB vCore database name to use with Azure Cosmos DB. + public string DatabaseName { get; } + /// The name of the Azure Cosmos DB resource container. + public string ContainerName { get; } + /// The MongoDB vCore index name to use with Azure Cosmos DB. + public string IndexName { get; } + /// Customized field mapping behavior to use when interacting with the search index. + public AzureCosmosDBFieldMappingOptions FieldMappingOptions { get; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.Serialization.cs new file mode 100644 index 000000000000..45fecca0fa9c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.Serialization.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureCosmosDBFieldMappingOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureCosmosDBFieldMappingOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(TitleFieldName)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleFieldName); + } + if (Optional.IsDefined(UrlFieldName)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlFieldName); + } + if (Optional.IsDefined(FilepathFieldName)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathFieldName); + } + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ContentFieldSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldSeparator); + } + writer.WritePropertyName("vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in VectorFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureCosmosDBFieldMappingOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureCosmosDBFieldMappingOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureCosmosDBFieldMappingOptions(document.RootElement, options); + } + + internal static AzureCosmosDBFieldMappingOptions DeserializeAzureCosmosDBFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string titleField = default; + string urlField = default; + string filepathField = default; + IList contentFields = default; + string contentFieldsSeparator = default; + IList vectorFields = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (property.NameEquals("vector_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorFields = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureCosmosDBFieldMappingOptions( + titleField, + urlField, + filepathField, + contentFields, + contentFieldsSeparator, + vectorFields, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureCosmosDBFieldMappingOptions)} does not support writing '{options.Format}' format."); + } + } + + AzureCosmosDBFieldMappingOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureCosmosDBFieldMappingOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureCosmosDBFieldMappingOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureCosmosDBFieldMappingOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureCosmosDBFieldMappingOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.cs new file mode 100644 index 000000000000..aff56c9de289 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureCosmosDBFieldMappingOptions.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Optional settings to control how fields are processed when using a configured Azure Cosmos DB resource. + public partial class AzureCosmosDBFieldMappingOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The names of index fields that should be treated as content. + /// The names of fields that represent vector data. + /// or is null. + public AzureCosmosDBFieldMappingOptions(IEnumerable contentFieldNames, IEnumerable vectorFieldNames) + { + Argument.AssertNotNull(contentFieldNames, nameof(contentFieldNames)); + Argument.AssertNotNull(vectorFieldNames, nameof(vectorFieldNames)); + + ContentFieldNames = contentFieldNames.ToList(); + VectorFieldNames = vectorFieldNames.ToList(); + } + + /// Initializes a new instance of . + /// The name of the index field to use as a title. + /// The name of the index field to use as a URL. + /// The name of the index field to use as a filepath. + /// The names of index fields that should be treated as content. + /// The separator pattern that content fields should use. + /// The names of fields that represent vector data. + /// Keeps track of any properties unknown to the library. + internal AzureCosmosDBFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IDictionary serializedAdditionalRawData) + { + TitleFieldName = titleFieldName; + UrlFieldName = urlFieldName; + FilepathFieldName = filepathFieldName; + ContentFieldNames = contentFieldNames; + ContentFieldSeparator = contentFieldSeparator; + VectorFieldNames = vectorFieldNames; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureCosmosDBFieldMappingOptions() + { + } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + /// The names of fields that represent vector data. + public IList VectorFieldNames { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.Serialization.cs new file mode 100644 index 000000000000..f156b75d3882 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancement : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancement)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("lines"u8); + writer.WriteStartArray(); + foreach (var item in Lines) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureGroundingEnhancement IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancement)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancement(document.RootElement, options); + } + + internal static AzureGroundingEnhancement DeserializeAzureGroundingEnhancement(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList lines = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("lines"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureGroundingEnhancementLine.DeserializeAzureGroundingEnhancementLine(item, options)); + } + lines = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancement(lines, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancement)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancement IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancement(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancement)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancement FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancement(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.cs new file mode 100644 index 000000000000..c0194b3dfa44 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancement.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The grounding enhancement that returns the bounding box of the objects detected in the image. + public partial class AzureGroundingEnhancement + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The lines of text detected by the grounding enhancement. + /// is null. + internal AzureGroundingEnhancement(IEnumerable lines) + { + Argument.AssertNotNull(lines, nameof(lines)); + + Lines = lines.ToList(); + } + + /// Initializes a new instance of . + /// The lines of text detected by the grounding enhancement. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancement(IReadOnlyList lines, IDictionary serializedAdditionalRawData) + { + Lines = lines; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancement() + { + } + + /// The lines of text detected by the grounding enhancement. + public IReadOnlyList Lines { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.Serialization.cs new file mode 100644 index 000000000000..980de43831bc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancementCoordinatePoint : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancementCoordinatePoint)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("x"u8); + writer.WriteNumberValue(X); + writer.WritePropertyName("y"u8); + writer.WriteNumberValue(Y); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureGroundingEnhancementCoordinatePoint IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancementCoordinatePoint)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancementCoordinatePoint(document.RootElement, options); + } + + internal static AzureGroundingEnhancementCoordinatePoint DeserializeAzureGroundingEnhancementCoordinatePoint(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + float x = default; + float y = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("x"u8)) + { + x = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("y"u8)) + { + y = property.Value.GetSingle(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancementCoordinatePoint(x, y, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementCoordinatePoint)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancementCoordinatePoint IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancementCoordinatePoint(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementCoordinatePoint)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancementCoordinatePoint FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancementCoordinatePoint(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.cs new file mode 100644 index 000000000000..44b5c9dcbd18 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementCoordinatePoint.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of a single polygon point as used by the Azure grounding enhancement. + public partial class AzureGroundingEnhancementCoordinatePoint + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The x-coordinate (horizontal axis) of the point. + /// The y-coordinate (vertical axis) of the point. + internal AzureGroundingEnhancementCoordinatePoint(float x, float y) + { + X = x; + Y = y; + } + + /// Initializes a new instance of . + /// The x-coordinate (horizontal axis) of the point. + /// The y-coordinate (vertical axis) of the point. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancementCoordinatePoint(float x, float y, IDictionary serializedAdditionalRawData) + { + X = x; + Y = y; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancementCoordinatePoint() + { + } + + /// The x-coordinate (horizontal axis) of the point. + public float X { get; } + /// The y-coordinate (vertical axis) of the point. + public float Y { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.Serialization.cs new file mode 100644 index 000000000000..4d652671b62d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancementLine : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLine)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("spans"u8); + writer.WriteStartArray(); + foreach (var item in Spans) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureGroundingEnhancementLine IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLine)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancementLine(document.RootElement, options); + } + + internal static AzureGroundingEnhancementLine DeserializeAzureGroundingEnhancementLine(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + IReadOnlyList spans = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("spans"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureGroundingEnhancementLineSpan.DeserializeAzureGroundingEnhancementLineSpan(item, options)); + } + spans = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancementLine(text, spans, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLine)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancementLine IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancementLine(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLine)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancementLine FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancementLine(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.cs new file mode 100644 index 000000000000..5ce268709106 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLine.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A content line object consisting of an adjacent sequence of content elements, such as words and selection marks. + public partial class AzureGroundingEnhancementLine + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The text within the line. + /// An array of spans that represent detected objects and its bounding box information. + /// or is null. + internal AzureGroundingEnhancementLine(string text, IEnumerable spans) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(spans, nameof(spans)); + + Text = text; + Spans = spans.ToList(); + } + + /// Initializes a new instance of . + /// The text within the line. + /// An array of spans that represent detected objects and its bounding box information. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancementLine(string text, IReadOnlyList spans, IDictionary serializedAdditionalRawData) + { + Text = text; + Spans = spans; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancementLine() + { + } + + /// The text within the line. + public string Text { get; } + /// An array of spans that represent detected objects and its bounding box information. + public IReadOnlyList Spans { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.Serialization.cs new file mode 100644 index 000000000000..8bbff8bdd3cc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.Serialization.cs @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureGroundingEnhancementLineSpan : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLineSpan)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("offset"u8); + writer.WriteNumberValue(Offset); + writer.WritePropertyName("length"u8); + writer.WriteNumberValue(Length); + writer.WritePropertyName("polygon"u8); + writer.WriteStartArray(); + foreach (var item in Polygon) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureGroundingEnhancementLineSpan IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLineSpan)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureGroundingEnhancementLineSpan(document.RootElement, options); + } + + internal static AzureGroundingEnhancementLineSpan DeserializeAzureGroundingEnhancementLineSpan(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + int offset = default; + int length = default; + IReadOnlyList polygon = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("offset"u8)) + { + offset = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("length"u8)) + { + length = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("polygon"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureGroundingEnhancementCoordinatePoint.DeserializeAzureGroundingEnhancementCoordinatePoint(item, options)); + } + polygon = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureGroundingEnhancementLineSpan(text, offset, length, polygon, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLineSpan)} does not support writing '{options.Format}' format."); + } + } + + AzureGroundingEnhancementLineSpan IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancementLineSpan(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureGroundingEnhancementLineSpan)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureGroundingEnhancementLineSpan FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureGroundingEnhancementLineSpan(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.cs new file mode 100644 index 000000000000..0c370dd4d762 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureGroundingEnhancementLineSpan.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A span object that represents a detected object and its bounding box information. + public partial class AzureGroundingEnhancementLineSpan + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The text content of the span that represents the detected object. + /// + /// 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. + /// + /// The length of the span in characters, measured in Unicode codepoints. + /// An array of objects representing points in the polygon that encloses the detected object. + /// or is null. + internal AzureGroundingEnhancementLineSpan(string text, int offset, int length, IEnumerable polygon) + { + Argument.AssertNotNull(text, nameof(text)); + Argument.AssertNotNull(polygon, nameof(polygon)); + + Text = text; + Offset = offset; + Length = length; + Polygon = polygon.ToList(); + } + + /// Initializes a new instance of . + /// The text content of the span that represents the detected object. + /// + /// 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. + /// + /// The length of the span in characters, measured in Unicode codepoints. + /// An array of objects representing points in the polygon that encloses the detected object. + /// Keeps track of any properties unknown to the library. + internal AzureGroundingEnhancementLineSpan(string text, int offset, int length, IReadOnlyList polygon, IDictionary serializedAdditionalRawData) + { + Text = text; + Offset = offset; + Length = length; + Polygon = polygon; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureGroundingEnhancementLineSpan() + { + } + + /// The text content of the span that represents the detected object. + public string Text { get; } + /// + /// 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. + /// + public int Offset { get; } + /// The length of the span in characters, measured in Unicode codepoints. + public int Length { get; } + /// An array of objects representing points in the polygon that encloses the detected object. + public IReadOnlyList Polygon { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..627a03972ef6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureSearchChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureSearchChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + } + + AzureSearchChatExtensionConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureSearchChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureSearchChatExtensionConfiguration(document.RootElement, options); + } + + internal static AzureSearchChatExtensionConfiguration DeserializeAzureSearchChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureSearchChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = AzureSearchChatExtensionParameters.DeserializeAzureSearchChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureSearchChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureSearchChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureSearchChatExtensionConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureSearchChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureSearchChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new AzureSearchChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureSearchChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.cs new file mode 100644 index 000000000000..5123cfe7c574 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Azure Search when using it as an Azure OpenAI chat + /// extension. + /// + public partial class AzureSearchChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Azure Search. + /// is null. + public AzureSearchChatExtensionConfiguration(AzureSearchChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.AzureSearch; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Azure Search. + internal AzureSearchChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, AzureSearchChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal AzureSearchChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Azure Search. + public AzureSearchChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.Serialization.cs new file mode 100644 index 000000000000..bd33b793b4e2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.Serialization.cs @@ -0,0 +1,347 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureSearchChatExtensionParameters : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(DocumentCount)) + { + writer.WritePropertyName("top_n_documents"u8); + writer.WriteNumberValue(DocumentCount.Value); + } + if (Optional.IsDefined(ShouldRestrictResultScope)) + { + writer.WritePropertyName("in_scope"u8); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); + } + if (Optional.IsDefined(Strictness)) + { + writer.WritePropertyName("strictness"u8); + writer.WriteNumberValue(Strictness.Value); + } + if (Optional.IsDefined(MaxSearchQueries)) + { + writer.WritePropertyName("max_search_queries"u8); + writer.WriteNumberValue(MaxSearchQueries.Value); + } + if (Optional.IsDefined(AllowPartialResult)) + { + writer.WritePropertyName("allow_partial_result"u8); + writer.WriteBooleanValue(AllowPartialResult.Value); + } + if (Optional.IsCollectionDefined(IncludeContexts)) + { + writer.WritePropertyName("include_contexts"u8); + writer.WriteStartArray(); + foreach (var item in IncludeContexts) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Authentication)) + { + writer.WritePropertyName("authentication"u8); + writer.WriteObjectValue(Authentication, options); + } + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(SearchEndpoint.AbsoluteUri); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + if (Optional.IsDefined(FieldMappingOptions)) + { + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldMappingOptions, options); + } + if (Optional.IsDefined(QueryType)) + { + writer.WritePropertyName("query_type"u8); + writer.WriteStringValue(QueryType.Value.ToString()); + } + if (Optional.IsDefined(SemanticConfiguration)) + { + writer.WritePropertyName("semantic_configuration"u8); + writer.WriteStringValue(SemanticConfiguration); + } + if (Optional.IsDefined(Filter)) + { + writer.WritePropertyName("filter"u8); + writer.WriteStringValue(Filter); + } + if (Optional.IsDefined(EmbeddingDependency)) + { + writer.WritePropertyName("embedding_dependency"u8); + writer.WriteObjectValue(EmbeddingDependency, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureSearchChatExtensionParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureSearchChatExtensionParameters(document.RootElement, options); + } + + internal static AzureSearchChatExtensionParameters DeserializeAzureSearchChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? topNDocuments = default; + bool? inScope = default; + int? strictness = default; + int? maxSearchQueries = default; + bool? allowPartialResult = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; + Uri endpoint = default; + string indexName = default; + AzureSearchIndexFieldMappingOptions fieldsMapping = default; + AzureSearchQueryType? queryType = default; + string semanticConfiguration = default; + string filter = default; + OnYourDataVectorizationSource embeddingDependency = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("top_n_documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topNDocuments = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("in_scope"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inScope = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("strictness"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + strictness = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_search_queries"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxSearchQueries = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("allow_partial_result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + allowPartialResult = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("include_contexts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new OnYourDataContextProperty(item.GetString())); + } + includeContexts = array; + continue; + } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); + continue; + } + if (property.NameEquals("endpoint"u8)) + { + endpoint = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("index_name"u8)) + { + indexName = property.Value.GetString(); + continue; + } + if (property.NameEquals("fields_mapping"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fieldsMapping = AzureSearchIndexFieldMappingOptions.DeserializeAzureSearchIndexFieldMappingOptions(property.Value, options); + continue; + } + if (property.NameEquals("query_type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + queryType = new AzureSearchQueryType(property.Value.GetString()); + continue; + } + if (property.NameEquals("semantic_configuration"u8)) + { + semanticConfiguration = property.Value.GetString(); + continue; + } + if (property.NameEquals("filter"u8)) + { + filter = property.Value.GetString(); + continue; + } + if (property.NameEquals("embedding_dependency"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureSearchChatExtensionParameters( + topNDocuments, + inScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts ?? new ChangeTrackingList(), + authentication, + endpoint, + indexName, + fieldsMapping, + queryType, + semanticConfiguration, + filter, + embeddingDependency, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support writing '{options.Format}' format."); + } + } + + AzureSearchChatExtensionParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureSearchChatExtensionParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureSearchChatExtensionParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureSearchChatExtensionParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureSearchChatExtensionParameters(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.cs new file mode 100644 index 000000000000..ad1430d18c2f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchChatExtensionParameters.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters for Azure Cognitive Search when used as an Azure OpenAI chat extension. The supported authentication types are APIKey, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. + public partial class AzureSearchChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + /// or is null. + public AzureSearchChatExtensionParameters(Uri searchEndpoint, string indexName) + { + Argument.AssertNotNull(searchEndpoint, nameof(searchEndpoint)); + Argument.AssertNotNull(indexName, nameof(indexName)); + + IncludeContexts = new ChangeTrackingList(); + SearchEndpoint = searchEndpoint; + IndexName = indexName; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + /// Customized field mapping behavior to use when interacting with the search index. + /// The query type to use with Azure Cognitive Search. + /// The additional semantic configuration for the query. + /// Search filter. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal AzureSearchChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, Uri searchEndpoint, string indexName, AzureSearchIndexFieldMappingOptions fieldMappingOptions, AzureSearchQueryType? queryType, string semanticConfiguration, string filter, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + SearchEndpoint = searchEndpoint; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + QueryType = queryType; + SemanticConfiguration = semanticConfiguration; + Filter = filter; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal AzureSearchChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The absolute endpoint path for the Azure Cognitive Search resource to use. + public Uri SearchEndpoint { get; } + /// The name of the index to use as available in the referenced Azure Cognitive Search resource. + public string IndexName { get; } + /// Customized field mapping behavior to use when interacting with the search index. + public AzureSearchIndexFieldMappingOptions FieldMappingOptions { get; set; } + /// The query type to use with Azure Cognitive Search. + public AzureSearchQueryType? QueryType { get; set; } + /// The additional semantic configuration for the query. + public string SemanticConfiguration { get; set; } + /// Search filter. + public string Filter { get; set; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.Serialization.cs new file mode 100644 index 000000000000..ee518a4ad222 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.Serialization.cs @@ -0,0 +1,261 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class AzureSearchIndexFieldMappingOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(TitleFieldName)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleFieldName); + } + if (Optional.IsDefined(UrlFieldName)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlFieldName); + } + if (Optional.IsDefined(FilepathFieldName)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathFieldName); + } + if (Optional.IsCollectionDefined(ContentFieldNames)) + { + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(ContentFieldSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldSeparator); + } + if (Optional.IsCollectionDefined(VectorFieldNames)) + { + writer.WritePropertyName("vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in VectorFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsCollectionDefined(ImageVectorFieldNames)) + { + writer.WritePropertyName("image_vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in ImageVectorFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + AzureSearchIndexFieldMappingOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureSearchIndexFieldMappingOptions(document.RootElement, options); + } + + internal static AzureSearchIndexFieldMappingOptions DeserializeAzureSearchIndexFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string titleField = default; + string urlField = default; + string filepathField = default; + IList contentFields = default; + string contentFieldsSeparator = default; + IList vectorFields = default; + IList imageVectorFields = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (property.NameEquals("vector_fields"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorFields = array; + continue; + } + if (property.NameEquals("image_vector_fields"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + imageVectorFields = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new AzureSearchIndexFieldMappingOptions( + titleField, + urlField, + filepathField, + contentFields ?? new ChangeTrackingList(), + contentFieldsSeparator, + vectorFields ?? new ChangeTrackingList(), + imageVectorFields ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support writing '{options.Format}' format."); + } + } + + AzureSearchIndexFieldMappingOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureSearchIndexFieldMappingOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureSearchIndexFieldMappingOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static AzureSearchIndexFieldMappingOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureSearchIndexFieldMappingOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.cs new file mode 100644 index 000000000000..cd659dda5d7f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchIndexFieldMappingOptions.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Optional settings to control how fields are processed when using a configured Azure Search resource. + public partial class AzureSearchIndexFieldMappingOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public AzureSearchIndexFieldMappingOptions() + { + ContentFieldNames = new ChangeTrackingList(); + VectorFieldNames = new ChangeTrackingList(); + ImageVectorFieldNames = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The name of the index field to use as a title. + /// The name of the index field to use as a URL. + /// The name of the index field to use as a filepath. + /// The names of index fields that should be treated as content. + /// The separator pattern that content fields should use. + /// The names of fields that represent vector data. + /// The names of fields that represent image vector data. + /// Keeps track of any properties unknown to the library. + internal AzureSearchIndexFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IList imageVectorFieldNames, IDictionary serializedAdditionalRawData) + { + TitleFieldName = titleFieldName; + UrlFieldName = urlFieldName; + FilepathFieldName = filepathFieldName; + ContentFieldNames = contentFieldNames; + ContentFieldSeparator = contentFieldSeparator; + VectorFieldNames = vectorFieldNames; + ImageVectorFieldNames = imageVectorFieldNames; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + /// The names of fields that represent vector data. + public IList VectorFieldNames { get; } + /// The names of fields that represent image vector data. + public IList ImageVectorFieldNames { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchQueryType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchQueryType.cs new file mode 100644 index 000000000000..98b220dec5f2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/AzureSearchQueryType.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The type of Azure Search retrieval query that should be executed when using it as an Azure OpenAI chat extension. + public readonly partial struct AzureSearchQueryType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public AzureSearchQueryType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "simple"; + private const string SemanticValue = "semantic"; + private const string VectorValue = "vector"; + private const string VectorSimpleHybridValue = "vector_simple_hybrid"; + private const string VectorSemanticHybridValue = "vector_semantic_hybrid"; + + /// Represents the default, simple query parser. + public static AzureSearchQueryType Simple { get; } = new AzureSearchQueryType(SimpleValue); + /// Represents the semantic query parser for advanced semantic modeling. + public static AzureSearchQueryType Semantic { get; } = new AzureSearchQueryType(SemanticValue); + /// Represents vector search over computed data. + public static AzureSearchQueryType Vector { get; } = new AzureSearchQueryType(VectorValue); + /// Represents a combination of the simple query strategy with vector data. + public static AzureSearchQueryType VectorSimpleHybrid { get; } = new AzureSearchQueryType(VectorSimpleHybridValue); + /// Represents a combination of semantic search and vector data querying. + public static AzureSearchQueryType VectorSemanticHybrid { get; } = new AzureSearchQueryType(VectorSemanticHybridValue); + /// Determines if two values are the same. + public static bool operator ==(AzureSearchQueryType left, AzureSearchQueryType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(AzureSearchQueryType left, AzureSearchQueryType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator AzureSearchQueryType(string value) => new AzureSearchQueryType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is AzureSearchQueryType other && Equals(other); + /// + public bool Equals(AzureSearchQueryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.Serialization.cs new file mode 100644 index 000000000000..6cf4e789ba04 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.Serialization.cs @@ -0,0 +1,429 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class Batch : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAI.Batch)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsDefined(Endpoint)) + { + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint); + } + if (Optional.IsDefined(Errors)) + { + writer.WritePropertyName("errors"u8); + writer.WriteObjectValue(Errors, options); + } + writer.WritePropertyName("input_file_id"u8); + writer.WriteStringValue(InputFileId); + if (Optional.IsDefined(CompletionWindow)) + { + writer.WritePropertyName("completion_window"u8); + writer.WriteStringValue(CompletionWindow); + } + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(OutputFileId)) + { + writer.WritePropertyName("output_file_id"u8); + writer.WriteStringValue(OutputFileId); + } + if (Optional.IsDefined(ErrorFileId)) + { + writer.WritePropertyName("error_file_id"u8); + writer.WriteStringValue(ErrorFileId); + } + if (Optional.IsDefined(CreatedAt)) + { + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt.Value, "U"); + } + if (Optional.IsDefined(InProgressAt)) + { + writer.WritePropertyName("in_progress_at"u8); + writer.WriteNumberValue(InProgressAt.Value, "U"); + } + if (Optional.IsDefined(ExpiresAt)) + { + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt.Value, "U"); + } + if (Optional.IsDefined(FinalizingAt)) + { + writer.WritePropertyName("finalizing_at"u8); + writer.WriteNumberValue(FinalizingAt.Value, "U"); + } + if (Optional.IsDefined(CompletedAt)) + { + writer.WritePropertyName("completed_at"u8); + writer.WriteNumberValue(CompletedAt.Value, "U"); + } + if (Optional.IsDefined(FailedAt)) + { + writer.WritePropertyName("failed_at"u8); + writer.WriteNumberValue(FailedAt.Value, "U"); + } + if (Optional.IsDefined(ExpiredAt)) + { + writer.WritePropertyName("expired_at"u8); + writer.WriteNumberValue(ExpiredAt.Value, "U"); + } + if (Optional.IsDefined(CancellingAt)) + { + writer.WritePropertyName("cancelling_at"u8); + writer.WriteNumberValue(CancellingAt.Value, "U"); + } + if (Optional.IsDefined(CancelledAt)) + { + writer.WritePropertyName("cancelled_at"u8); + writer.WriteNumberValue(CancelledAt.Value, "U"); + } + if (Optional.IsDefined(RequestCounts)) + { + writer.WritePropertyName("request_counts"u8); + writer.WriteObjectValue(RequestCounts, options); + } + if (Optional.IsCollectionDefined(Metadata)) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OpenAI.Batch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAI.Batch)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return OpenAI.Batch.DeserializeBatch(document.RootElement, options); + } + + internal static OpenAI.Batch DeserializeBatch(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + BatchObject @object = default; + string endpoint = default; + BatchErrorList errors = default; + string inputFileId = default; + string completionWindow = default; + BatchStatus? status = default; + string outputFileId = default; + string errorFileId = default; + DateTimeOffset? createdAt = default; + DateTimeOffset? inProgressAt = default; + DateTimeOffset? expiresAt = default; + DateTimeOffset? finalizingAt = default; + DateTimeOffset? completedAt = default; + DateTimeOffset? failedAt = default; + DateTimeOffset? expiredAt = default; + DateTimeOffset? cancellingAt = default; + DateTimeOffset? cancelledAt = default; + BatchRequestCounts requestCounts = default; + IReadOnlyDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new BatchObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("endpoint"u8)) + { + endpoint = property.Value.GetString(); + continue; + } + if (property.NameEquals("errors"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + errors = BatchErrorList.DeserializeBatchErrorList(property.Value, options); + continue; + } + if (property.NameEquals("input_file_id"u8)) + { + inputFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("completion_window"u8)) + { + completionWindow = property.Value.GetString(); + continue; + } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new BatchStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("output_file_id"u8)) + { + outputFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("error_file_id"u8)) + { + errorFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("in_progress_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inProgressAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("finalizing_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + finalizingAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("completed_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + completedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("failed_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + failedAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("expired_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + expiredAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("cancelling_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + cancellingAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("cancelled_at"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + cancelledAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("request_counts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + requestCounts = BatchRequestCounts.DeserializeBatchRequestCounts(property.Value, options); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAI.Batch( + id, + @object, + endpoint, + errors, + inputFileId, + completionWindow, + status, + outputFileId, + errorFileId, + createdAt, + inProgressAt, + expiresAt, + finalizingAt, + completedAt, + failedAt, + expiredAt, + cancellingAt, + cancelledAt, + requestCounts, + metadata ?? new ChangeTrackingDictionary(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OpenAI.Batch)} does not support writing '{options.Format}' format."); + } + } + + OpenAI.Batch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return OpenAI.Batch.DeserializeBatch(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAI.Batch)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAI.Batch FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return OpenAI.Batch.DeserializeBatch(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.cs new file mode 100644 index 000000000000..6bed6d1a92f9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Batch.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The Batch object. + internal partial class Batch + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The id assigned to the Batch. + /// The ID of the input file for the batch. + /// or is null. + internal Batch(string id, string inputFileId) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(inputFileId, nameof(inputFileId)); + + Id = id; + InputFileId = inputFileId; + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The id assigned to the Batch. + /// The object type, which is always `batch`. + /// The OpenAI API endpoint used by the batch. + /// The list of Batch errors. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// The current status of the batch. + /// The ID of the file containing the outputs of successfully executed requests. + /// The ID of the file containing the outputs of requests with errors. + /// The Unix timestamp (in seconds) for when the batch was created. + /// The Unix timestamp (in seconds) for when the batch started processing. + /// The Unix timestamp (in seconds) for when the batch will expire. + /// The Unix timestamp (in seconds) for when the batch started finalizing. + /// The Unix timestamp (in seconds) for when the batch was completed. + /// The Unix timestamp (in seconds) for when the batch failed. + /// The Unix timestamp (in seconds) for when the batch expired. + /// The Unix timestamp (in seconds) for when the batch started cancelling. + /// The Unix timestamp (in seconds) for when the batch was cancelled. + /// The request counts for different statuses within the batch. + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + /// Keeps track of any properties unknown to the library. + internal Batch(string id, BatchObject @object, string endpoint, BatchErrorList errors, string inputFileId, string completionWindow, BatchStatus? status, string outputFileId, string errorFileId, DateTimeOffset? createdAt, DateTimeOffset? inProgressAt, DateTimeOffset? expiresAt, DateTimeOffset? finalizingAt, DateTimeOffset? completedAt, DateTimeOffset? failedAt, DateTimeOffset? expiredAt, DateTimeOffset? cancellingAt, DateTimeOffset? cancelledAt, BatchRequestCounts requestCounts, IReadOnlyDictionary metadata, IDictionary serializedAdditionalRawData) + { + Id = id; + Object = @object; + Endpoint = endpoint; + Errors = errors; + InputFileId = inputFileId; + CompletionWindow = completionWindow; + Status = status; + OutputFileId = outputFileId; + ErrorFileId = errorFileId; + CreatedAt = createdAt; + InProgressAt = inProgressAt; + ExpiresAt = expiresAt; + FinalizingAt = finalizingAt; + CompletedAt = completedAt; + FailedAt = failedAt; + ExpiredAt = expiredAt; + CancellingAt = cancellingAt; + CancelledAt = cancelledAt; + RequestCounts = requestCounts; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Batch() + { + } + + /// The id assigned to the Batch. + public string Id { get; } + /// The object type, which is always `batch`. + public BatchObject Object { get; } = BatchObject.Batch; + + /// The OpenAI API endpoint used by the batch. + public string Endpoint { get; } + /// The list of Batch errors. + public BatchErrorList Errors { get; } + /// The ID of the input file for the batch. + public string InputFileId { get; } + /// The time frame within which the batch should be processed. + public string CompletionWindow { get; } + /// The current status of the batch. + public BatchStatus? Status { get; } + /// The ID of the file containing the outputs of successfully executed requests. + public string OutputFileId { get; } + /// The ID of the file containing the outputs of requests with errors. + public string ErrorFileId { get; } + /// The Unix timestamp (in seconds) for when the batch was created. + public DateTimeOffset? CreatedAt { get; } + /// The Unix timestamp (in seconds) for when the batch started processing. + public DateTimeOffset? InProgressAt { get; } + /// The Unix timestamp (in seconds) for when the batch will expire. + public DateTimeOffset? ExpiresAt { get; } + /// The Unix timestamp (in seconds) for when the batch started finalizing. + public DateTimeOffset? FinalizingAt { get; } + /// The Unix timestamp (in seconds) for when the batch was completed. + public DateTimeOffset? CompletedAt { get; } + /// The Unix timestamp (in seconds) for when the batch failed. + public DateTimeOffset? FailedAt { get; } + /// The Unix timestamp (in seconds) for when the batch expired. + public DateTimeOffset? ExpiredAt { get; } + /// The Unix timestamp (in seconds) for when the batch started cancelling. + public DateTimeOffset? CancellingAt { get; } + /// The Unix timestamp (in seconds) for when the batch was cancelled. + public DateTimeOffset? CancelledAt { get; } + /// The request counts for different statuses within the batch. + public BatchRequestCounts RequestCounts { get; } + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + public IReadOnlyDictionary Metadata { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.Serialization.cs new file mode 100644 index 000000000000..dc6a24b4e5d3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.Serialization.cs @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class BatchCreateRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchCreateRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint); + writer.WritePropertyName("input_file_id"u8); + writer.WriteStringValue(InputFileId); + writer.WritePropertyName("completion_window"u8); + writer.WriteStringValue(CompletionWindow); + if (Optional.IsCollectionDefined(Metadata)) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BatchCreateRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchCreateRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchCreateRequest(document.RootElement, options); + } + + internal static BatchCreateRequest DeserializeBatchCreateRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string endpoint = default; + string inputFileId = default; + string completionWindow = default; + IDictionary metadata = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("endpoint"u8)) + { + endpoint = property.Value.GetString(); + continue; + } + if (property.NameEquals("input_file_id"u8)) + { + inputFileId = property.Value.GetString(); + continue; + } + if (property.NameEquals("completion_window"u8)) + { + completionWindow = property.Value.GetString(); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchCreateRequest(endpoint, inputFileId, completionWindow, metadata ?? new ChangeTrackingDictionary(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(BatchCreateRequest)} does not support writing '{options.Format}' format."); + } + } + + BatchCreateRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchCreateRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchCreateRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchCreateRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchCreateRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.cs new file mode 100644 index 000000000000..b041ee731672 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchCreateRequest.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Defines the request to create a batch. + public partial class BatchCreateRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The API endpoint used by the batch. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// , or is null. + public BatchCreateRequest(string endpoint, string inputFileId, string completionWindow) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(inputFileId, nameof(inputFileId)); + Argument.AssertNotNull(completionWindow, nameof(completionWindow)); + + Endpoint = endpoint; + InputFileId = inputFileId; + CompletionWindow = completionWindow; + Metadata = new ChangeTrackingDictionary(); + } + + /// Initializes a new instance of . + /// The API endpoint used by the batch. + /// The ID of the input file for the batch. + /// The time frame within which the batch should be processed. + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + /// Keeps track of any properties unknown to the library. + internal BatchCreateRequest(string endpoint, string inputFileId, string completionWindow, IDictionary metadata, IDictionary serializedAdditionalRawData) + { + Endpoint = endpoint; + InputFileId = inputFileId; + CompletionWindow = completionWindow; + Metadata = metadata; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal BatchCreateRequest() + { + } + + /// The API endpoint used by the batch. + public string Endpoint { get; } + /// The ID of the input file for the batch. + public string InputFileId { get; } + /// The time frame within which the batch should be processed. + public string CompletionWindow { get; } + /// A set of key-value pairs that can be attached to the batch. This can be useful for storing additional information about the batch in a structured format. + public IDictionary Metadata { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.Serialization.cs new file mode 100644 index 000000000000..27fc2042840f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.Serialization.cs @@ -0,0 +1,182 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class BatchErrorDatum : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchErrorDatum)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Code)) + { + writer.WritePropertyName("code"u8); + writer.WriteStringValue(Code); + } + if (Optional.IsDefined(Message)) + { + writer.WritePropertyName("message"u8); + writer.WriteStringValue(Message); + } + if (Optional.IsDefined(Param)) + { + writer.WritePropertyName("param"u8); + writer.WriteStringValue(Param); + } + if (Optional.IsDefined(Line)) + { + writer.WritePropertyName("line"u8); + writer.WriteNumberValue(Line.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BatchErrorDatum IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchErrorDatum)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchErrorDatum(document.RootElement, options); + } + + internal static BatchErrorDatum DeserializeBatchErrorDatum(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string code = default; + string message = default; + string param = default; + int? line = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("code"u8)) + { + code = property.Value.GetString(); + continue; + } + if (property.NameEquals("message"u8)) + { + message = property.Value.GetString(); + continue; + } + if (property.NameEquals("param"u8)) + { + param = property.Value.GetString(); + continue; + } + if (property.NameEquals("line"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + line = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchErrorDatum(code, message, param, line, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(BatchErrorDatum)} does not support writing '{options.Format}' format."); + } + } + + BatchErrorDatum IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchErrorDatum(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchErrorDatum)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchErrorDatum FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchErrorDatum(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.cs new file mode 100644 index 000000000000..456d267b86e9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorDatum.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A Datum containing information about a Batch Error. + internal partial class BatchErrorDatum + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal BatchErrorDatum() + { + } + + /// Initializes a new instance of . + /// An error code identifying the error type. + /// A human-readable message providing more details about the error. + /// The name of the parameter that caused the error, if applicable. + /// The line number of the input file where the error occurred, if applicable. + /// Keeps track of any properties unknown to the library. + internal BatchErrorDatum(string code, string message, string param, int? line, IDictionary serializedAdditionalRawData) + { + Code = code; + Message = message; + Param = param; + Line = line; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// An error code identifying the error type. + public string Code { get; } + /// A human-readable message providing more details about the error. + public string Message { get; } + /// The name of the parameter that caused the error, if applicable. + public string Param { get; } + /// The line number of the input file where the error occurred, if applicable. + public int? Line { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.Serialization.cs new file mode 100644 index 000000000000..67c61822dd77 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.Serialization.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class BatchErrorList : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchErrorList)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsCollectionDefined(Data)) + { + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BatchErrorList IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchErrorList)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchErrorList(document.RootElement, options); + } + + internal static BatchErrorList DeserializeBatchErrorList(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BatchErrorListObject @object = default; + IReadOnlyList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new BatchErrorListObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("data"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(BatchErrorDatum.DeserializeBatchErrorDatum(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchErrorList(@object, data ?? new ChangeTrackingList(), serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(BatchErrorList)} does not support writing '{options.Format}' format."); + } + } + + BatchErrorList IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchErrorList(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchErrorList)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchErrorList FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchErrorList(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.cs new file mode 100644 index 000000000000..29f92fdc83cf --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorList.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A list of Batch errors. + internal partial class BatchErrorList + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal BatchErrorList() + { + Data = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The object type, which is always `list`. + /// The list of Batch error data. + /// Keeps track of any properties unknown to the library. + internal BatchErrorList(BatchErrorListObject @object, IReadOnlyList data, IDictionary serializedAdditionalRawData) + { + Object = @object; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type, which is always `list`. + public BatchErrorListObject Object { get; } = BatchErrorListObject.List; + + /// The list of Batch error data. + public IReadOnlyList Data { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorListObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorListObject.cs new file mode 100644 index 000000000000..55ccfecd62da --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchErrorListObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The BatchErrorList_object. + internal readonly partial struct BatchErrorListObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public BatchErrorListObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static BatchErrorListObject List { get; } = new BatchErrorListObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(BatchErrorListObject left, BatchErrorListObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(BatchErrorListObject left, BatchErrorListObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator BatchErrorListObject(string value) => new BatchErrorListObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is BatchErrorListObject other && Equals(other); + /// + public bool Equals(BatchErrorListObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchObject.cs new file mode 100644 index 000000000000..7d9b06bdf500 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The Batch_object. + internal readonly partial struct BatchObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public BatchObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string BatchValue = "batch"; + + /// batch. + public static BatchObject Batch { get; } = new BatchObject(BatchValue); + /// Determines if two values are the same. + public static bool operator ==(BatchObject left, BatchObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(BatchObject left, BatchObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator BatchObject(string value) => new BatchObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is BatchObject other && Equals(other); + /// + public bool Equals(BatchObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.Serialization.cs new file mode 100644 index 000000000000..be17ae202710 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.Serialization.cs @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class BatchRequestCounts : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchRequestCounts)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Total)) + { + writer.WritePropertyName("total"u8); + writer.WriteNumberValue(Total.Value); + } + if (Optional.IsDefined(Completed)) + { + writer.WritePropertyName("completed"u8); + writer.WriteNumberValue(Completed.Value); + } + if (Optional.IsDefined(Failed)) + { + writer.WritePropertyName("failed"u8); + writer.WriteNumberValue(Failed.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BatchRequestCounts IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchRequestCounts)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchRequestCounts(document.RootElement, options); + } + + internal static BatchRequestCounts DeserializeBatchRequestCounts(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? total = default; + int? completed = default; + int? failed = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("total"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + total = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("completed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + completed = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("failed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + failed = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchRequestCounts(total, completed, failed, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(BatchRequestCounts)} does not support writing '{options.Format}' format."); + } + } + + BatchRequestCounts IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchRequestCounts(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchRequestCounts)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchRequestCounts FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchRequestCounts(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.cs new file mode 100644 index 000000000000..014a428c108f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchRequestCounts.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The BatchRequestCounts. + internal partial class BatchRequestCounts + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal BatchRequestCounts() + { + } + + /// Initializes a new instance of . + /// Total number of requests in the batch. + /// Number of requests that have been completed successfully. + /// Number of requests that have failed. + /// Keeps track of any properties unknown to the library. + internal BatchRequestCounts(int? total, int? completed, int? failed, IDictionary serializedAdditionalRawData) + { + Total = total; + Completed = completed; + Failed = failed; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Total number of requests in the batch. + public int? Total { get; } + /// Number of requests that have been completed successfully. + public int? Completed { get; } + /// Number of requests that have failed. + public int? Failed { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchStatus.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchStatus.cs new file mode 100644 index 000000000000..421a0f16f186 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/BatchStatus.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The status of a batch. + internal readonly partial struct BatchStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public BatchStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ValidatingValue = "validating"; + private const string FailedValue = "failed"; + private const string InProgressValue = "in_progress"; + private const string FinalizingValue = "finalizing"; + private const string CompletedValue = "completed"; + private const string ExpiredValue = "expired"; + private const string CancellingValue = "cancelling"; + private const string CancelledValue = "cancelled"; + + /// The input file is being validated before the batch can begin. + public static BatchStatus Validating { get; } = new BatchStatus(ValidatingValue); + /// The input file has failed the validation process. + public static BatchStatus Failed { get; } = new BatchStatus(FailedValue); + /// The input file was successfully validated and the batch is currently being executed. + public static BatchStatus InProgress { get; } = new BatchStatus(InProgressValue); + /// The batch has completed and the results are being prepared. + public static BatchStatus Finalizing { get; } = new BatchStatus(FinalizingValue); + /// The batch has been completed and the results are ready. + public static BatchStatus Completed { get; } = new BatchStatus(CompletedValue); + /// The batch was not able to complete within the 24-hour time window. + public static BatchStatus Expired { get; } = new BatchStatus(ExpiredValue); + /// Cancellation of the batch has been initiated. + public static BatchStatus Cancelling { get; } = new BatchStatus(CancellingValue); + /// The batch was cancelled. + public static BatchStatus Cancelled { get; } = new BatchStatus(CancelledValue); + /// Determines if two values are the same. + public static bool operator ==(BatchStatus left, BatchStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(BatchStatus left, BatchStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator BatchStatus(string value) => new BatchStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is BatchStatus other && Equals(other); + /// + public bool Equals(BatchStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.Serialization.cs new file mode 100644 index 000000000000..75a5bf097870 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.Serialization.cs @@ -0,0 +1,250 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatChoice : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatChoice)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Message)) + { + writer.WritePropertyName("message"u8); + writer.WriteObjectValue(Message, options); + } + if (LogProbabilityInfo != null) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteObjectValue(LogProbabilityInfo, options); + } + else + { + writer.WriteNull("logprobs"); + } + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + if (FinishReason != null) + { + writer.WritePropertyName("finish_reason"u8); + writer.WriteStringValue(FinishReason.Value.ToString()); + } + else + { + writer.WriteNull("finish_reason"); + } + if (Optional.IsDefined(InternalStreamingDeltaMessage)) + { + writer.WritePropertyName("delta"u8); + writer.WriteObjectValue(InternalStreamingDeltaMessage, options); + } + if (Optional.IsDefined(ContentFilterResults)) + { + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); + } + if (Optional.IsDefined(Enhancements)) + { + writer.WritePropertyName("enhancements"u8); + writer.WriteObjectValue(Enhancements, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatChoice)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatChoice(document.RootElement, options); + } + + internal static ChatChoice DeserializeChatChoice(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatResponseMessage message = default; + ChatChoiceLogProbabilityInfo logprobs = default; + int index = default; + CompletionsFinishReason? finishReason = default; + ChatResponseMessage delta = default; + ContentFilterResultsForChoice contentFilterResults = default; + AzureChatEnhancements enhancements = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("message"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + message = ChatResponseMessage.DeserializeChatResponseMessage(property.Value, options); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + logprobs = null; + continue; + } + logprobs = ChatChoiceLogProbabilityInfo.DeserializeChatChoiceLogProbabilityInfo(property.Value, options); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("finish_reason"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + finishReason = null; + continue; + } + finishReason = new CompletionsFinishReason(property.Value.GetString()); + continue; + } + if (property.NameEquals("delta"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + delta = ChatResponseMessage.DeserializeChatResponseMessage(property.Value, options); + continue; + } + if (property.NameEquals("content_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + contentFilterResults = ContentFilterResultsForChoice.DeserializeContentFilterResultsForChoice(property.Value, options); + continue; + } + if (property.NameEquals("enhancements"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + enhancements = AzureChatEnhancements.DeserializeAzureChatEnhancements(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatChoice( + message, + logprobs, + index, + finishReason, + delta, + contentFilterResults, + enhancements, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatChoice)} does not support writing '{options.Format}' format."); + } + } + + ChatChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatChoice(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatChoice)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatChoice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatChoice(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.cs new file mode 100644 index 000000000000..4e85fb934a30 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoice.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class ChatChoice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + /// The ordered index associated with this chat completions choice. + /// The reason that this chat completions choice completed its generated. + internal ChatChoice(ChatChoiceLogProbabilityInfo logProbabilityInfo, int index, CompletionsFinishReason? finishReason) + { + LogProbabilityInfo = logProbabilityInfo; + Index = index; + FinishReason = finishReason; + } + + /// Initializes a new instance of . + /// The chat message for a given chat completions prompt. + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + /// The ordered index associated with this chat completions choice. + /// The reason that this chat completions choice completed its generated. + /// The delta message content for a streaming response. + /// + /// 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. + /// + /// + /// 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. + /// + /// Keeps track of any properties unknown to the library. + internal ChatChoice(ChatResponseMessage message, ChatChoiceLogProbabilityInfo logProbabilityInfo, int index, CompletionsFinishReason? finishReason, ChatResponseMessage internalStreamingDeltaMessage, ContentFilterResultsForChoice contentFilterResults, AzureChatEnhancements enhancements, IDictionary serializedAdditionalRawData) + { + Message = message; + LogProbabilityInfo = logProbabilityInfo; + Index = index; + FinishReason = finishReason; + InternalStreamingDeltaMessage = internalStreamingDeltaMessage; + ContentFilterResults = contentFilterResults; + Enhancements = enhancements; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatChoice() + { + } + + /// The chat message for a given chat completions prompt. + public ChatResponseMessage Message { get; } + /// The log probability information for this choice, as enabled via the 'logprobs' request option. + public ChatChoiceLogProbabilityInfo LogProbabilityInfo { get; } + /// The ordered index associated with this chat completions choice. + public int Index { get; } + /// The reason that this chat completions choice completed its generated. + public CompletionsFinishReason? FinishReason { get; } + /// The delta message content for a streaming response. + public ChatResponseMessage InternalStreamingDeltaMessage { get; } + /// + /// 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. + /// + public ContentFilterResultsForChoice ContentFilterResults { get; } + /// + /// 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. + /// + public AzureChatEnhancements Enhancements { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.Serialization.cs new file mode 100644 index 000000000000..0a7d41bf9eaa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.Serialization.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatChoiceLogProbabilityInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatChoiceLogProbabilityInfo)} does not support writing '{format}' format."); + } + + if (TokenLogProbabilityResults != null && Optional.IsCollectionDefined(TokenLogProbabilityResults)) + { + writer.WritePropertyName("content"u8); + writer.WriteStartArray(); + foreach (var item in TokenLogProbabilityResults) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("content"); + } + if (Refusal != null && Optional.IsCollectionDefined(Refusal)) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStartArray(); + foreach (var item in Refusal) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("refusal"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatChoiceLogProbabilityInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatChoiceLogProbabilityInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatChoiceLogProbabilityInfo(document.RootElement, options); + } + + internal static ChatChoiceLogProbabilityInfo DeserializeChatChoiceLogProbabilityInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList content = default; + IReadOnlyList refusal = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityResult.DeserializeChatTokenLogProbabilityResult(item, options)); + } + content = array; + continue; + } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityResult.DeserializeChatTokenLogProbabilityResult(item, options)); + } + refusal = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatChoiceLogProbabilityInfo(content, refusal, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatChoiceLogProbabilityInfo)} does not support writing '{options.Format}' format."); + } + } + + ChatChoiceLogProbabilityInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatChoiceLogProbabilityInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatChoiceLogProbabilityInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatChoiceLogProbabilityInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatChoiceLogProbabilityInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.cs new file mode 100644 index 000000000000..f2343104bd0a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatChoiceLogProbabilityInfo.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Log probability information for a choice, as requested via 'logprobs' and 'top_logprobs'. + public partial class ChatChoiceLogProbabilityInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + internal ChatChoiceLogProbabilityInfo(IEnumerable tokenLogProbabilityResults, IEnumerable refusal) + { + TokenLogProbabilityResults = tokenLogProbabilityResults?.ToList(); + Refusal = refusal?.ToList(); + } + + /// Initializes a new instance of . + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + /// Keeps track of any properties unknown to the library. + internal ChatChoiceLogProbabilityInfo(IReadOnlyList tokenLogProbabilityResults, IReadOnlyList refusal, IDictionary serializedAdditionalRawData) + { + TokenLogProbabilityResults = tokenLogProbabilityResults; + Refusal = refusal; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatChoiceLogProbabilityInfo() + { + } + + /// The list of log probability information entries for the choice's message content tokens, as requested via the 'logprobs' option. + public IReadOnlyList TokenLogProbabilityResults { get; } + /// The list of log probability information entries for the choice's message refusal message tokens, as requested via the 'logprobs' option. + public IReadOnlyList Refusal { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionModality.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionModality.cs new file mode 100644 index 000000000000..d2c266591d0e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionModality.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Values to specified the required modality for the model to use. + public readonly partial struct ChatCompletionModality : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatCompletionModality(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string TextValue = "text"; + private const string AudioValue = "audio"; + + /// The model is to generate text output. + public static ChatCompletionModality Text { get; } = new ChatCompletionModality(TextValue); + /// The model is to generate audio output. + public static ChatCompletionModality Audio { get; } = new ChatCompletionModality(AudioValue); + /// Determines if two values are the same. + public static bool operator ==(ChatCompletionModality left, ChatCompletionModality right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatCompletionModality left, ChatCompletionModality right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ChatCompletionModality(string value) => new ChatCompletionModality(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatCompletionModality other && Equals(other); + /// + public bool Equals(ChatCompletionModality other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.Serialization.cs new file mode 100644 index 000000000000..6e36e03a96fa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionStreamOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionStreamOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(IncludeUsage)) + { + writer.WritePropertyName("include_usage"u8); + writer.WriteBooleanValue(IncludeUsage.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionStreamOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionStreamOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionStreamOptions(document.RootElement, options); + } + + internal static ChatCompletionStreamOptions DeserializeChatCompletionStreamOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool? includeUsage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("include_usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + includeUsage = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionStreamOptions(includeUsage, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionStreamOptions)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionStreamOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionStreamOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionStreamOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionStreamOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionStreamOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.cs new file mode 100644 index 000000000000..2dba2eb70309 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionStreamOptions.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Options for streaming response. Only set this when you set `stream: true`. + public partial class ChatCompletionStreamOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public ChatCompletionStreamOptions() + { + } + + /// Initializes a new instance of . + /// If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionStreamOptions(bool? includeUsage, IDictionary serializedAdditionalRawData) + { + IncludeUsage = includeUsage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire request, and the `choices` field will always be an empty array. All other chunks will also include a `usage` field, but with a null value. + public bool? IncludeUsage { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.Serialization.cs new file mode 100644 index 000000000000..c463398f7c6e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.Serialization.cs @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(Created, "U"); + writer.WritePropertyName("choices"u8); + writer.WriteStartArray(); + foreach (var item in Choices) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsDefined(Model)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(Model); + } + if (Optional.IsCollectionDefined(PromptFilterResults)) + { + writer.WritePropertyName("prompt_filter_results"u8); + writer.WriteStartArray(); + foreach (var item in PromptFilterResults) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(SystemFingerprint)) + { + writer.WritePropertyName("system_fingerprint"u8); + writer.WriteStringValue(SystemFingerprint); + } + if (Optional.IsDefined(Usage)) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletions(document.RootElement, options); + } + + internal static ChatCompletions DeserializeChatCompletions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset created = default; + IReadOnlyList choices = default; + string model = default; + IReadOnlyList promptFilterResults = default; + string systemFingerprint = default; + CompletionsUsage usage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created"u8)) + { + created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("choices"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatChoice.DeserializeChatChoice(item, options)); + } + choices = array; + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("prompt_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ContentFilterResultsForPrompt.DeserializeContentFilterResultsForPrompt(item, options)); + } + promptFilterResults = array; + continue; + } + if (property.NameEquals("system_fingerprint"u8)) + { + systemFingerprint = property.Value.GetString(); + continue; + } + if (property.NameEquals("usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + usage = CompletionsUsage.DeserializeCompletionsUsage(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletions( + id, + created, + choices, + model, + promptFilterResults ?? new ChangeTrackingList(), + systemFingerprint, + usage, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletions)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.cs new file mode 100644 index 000000000000..a422703ccf3c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletions.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class ChatCompletions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A unique identifier associated with this chat completions response. + /// + /// 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. + /// + /// + /// 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. + /// + /// or is null. + internal ChatCompletions(string id, DateTimeOffset created, IEnumerable choices) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(choices, nameof(choices)); + + Id = id; + Created = created; + Choices = choices.ToList(); + PromptFilterResults = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// A unique identifier associated with this chat completions response. + /// + /// 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. + /// + /// + /// 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. + /// + /// The model name used for this completions request. + /// + /// 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. + /// + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that + /// might impact determinism. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// Keeps track of any properties unknown to the library. + internal ChatCompletions(string id, DateTimeOffset created, IReadOnlyList choices, string model, IReadOnlyList promptFilterResults, string systemFingerprint, CompletionsUsage usage, IDictionary serializedAdditionalRawData) + { + Id = id; + Created = created; + Choices = choices; + Model = model; + PromptFilterResults = promptFilterResults; + SystemFingerprint = systemFingerprint; + Usage = usage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletions() + { + } + + /// A unique identifier associated with this chat completions response. + public string Id { get; } + /// + /// 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. + /// + public DateTimeOffset Created { get; } + /// + /// 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. + /// + public IReadOnlyList Choices { get; } + /// The model name used for this completions request. + public string Model { get; } + /// + /// 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. + /// + public IReadOnlyList PromptFilterResults { get; } + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that + /// might impact determinism. + /// + public string SystemFingerprint { get; } + /// Usage information for tokens processed and generated as part of this completions operation. + public CompletionsUsage Usage { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.Serialization.cs new file mode 100644 index 000000000000..fda30fd5463d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.Serialization.cs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolCall)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } + + ChatCompletionsFunctionToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolCall(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolCall DeserializeChatCompletionsFunctionToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FunctionCall function = default; + string type = default; + string id = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + function = FunctionCall.DeserializeFunctionCall(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolCall(type, id, serializedAdditionalRawData, function); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolCall)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsFunctionToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolCall(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.cs new file mode 100644 index 000000000000..97a6d2211fd9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolCall.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class ChatCompletionsFunctionToolCall : ChatCompletionsToolCall + { + /// Initializes a new instance of . + /// The ID of the tool call. + /// The details of the function invocation requested by the tool call. + /// or is null. + public ChatCompletionsFunctionToolCall(string id, FunctionCall function) : base(id) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(function, nameof(function)); + + Type = "function"; + Function = function; + } + + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. + /// Keeps track of any properties unknown to the library. + /// The details of the function invocation requested by the tool call. + internal ChatCompletionsFunctionToolCall(string type, string id, IDictionary serializedAdditionalRawData, FunctionCall function) : base(type, id, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolCall() + { + } + + /// The details of the function invocation requested by the tool call. + public FunctionCall Function { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.Serialization.cs new file mode 100644 index 000000000000..3e81c6cc9d56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } + + ChatCompletionsFunctionToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolDefinition(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolDefinition DeserializeChatCompletionsFunctionToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatCompletionsFunctionToolDefinitionFunction function = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + function = ChatCompletionsFunctionToolDefinitionFunction.DeserializeChatCompletionsFunctionToolDefinitionFunction(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolDefinition(type, serializedAdditionalRawData, function); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinition)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsFunctionToolDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolDefinition(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.cs new file mode 100644 index 000000000000..7b1881366a9b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinition.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The definition information for a chat completions function tool that can call a function in response to a tool call. + public partial class ChatCompletionsFunctionToolDefinition : ChatCompletionsToolDefinition + { + /// Initializes a new instance of . + /// The function definition details for the function tool. + /// is null. + public ChatCompletionsFunctionToolDefinition(ChatCompletionsFunctionToolDefinitionFunction function) + { + Argument.AssertNotNull(function, nameof(function)); + + Type = "function"; + Function = function; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The function definition details for the function tool. + internal ChatCompletionsFunctionToolDefinition(string type, IDictionary serializedAdditionalRawData, ChatCompletionsFunctionToolDefinitionFunction function) : base(type, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolDefinition() + { + } + + /// The function definition details for the function tool. + public ChatCompletionsFunctionToolDefinitionFunction Function { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.Serialization.cs new file mode 100644 index 000000000000..10b0ee699dcd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.Serialization.cs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolDefinitionFunction : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinitionFunction)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Optional.IsDefined(Parameters)) + { + writer.WritePropertyName("parameters"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Parameters); +#else + using (JsonDocument document = JsonDocument.Parse(Parameters, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(Strict)) + { + if (Strict != null) + { + writer.WritePropertyName("strict"u8); + writer.WriteBooleanValue(Strict.Value); + } + else + { + writer.WriteNull("strict"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsFunctionToolDefinitionFunction IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinitionFunction)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolDefinitionFunction(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolDefinitionFunction DeserializeChatCompletionsFunctionToolDefinitionFunction(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string description = default; + string name = default; + BinaryData parameters = default; + bool? strict = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("parameters"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parameters = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("strict"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + strict = null; + continue; + } + strict = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolDefinitionFunction(description, name, parameters, strict, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinitionFunction)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolDefinitionFunction IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolDefinitionFunction(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolDefinitionFunction)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsFunctionToolDefinitionFunction FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolDefinitionFunction(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.cs new file mode 100644 index 000000000000..03c565925bbd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolDefinitionFunction.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The ChatCompletionsFunctionToolDefinitionFunction. + public partial class ChatCompletionsFunctionToolDefinitionFunction + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// is null. + public ChatCompletionsFunctionToolDefinitionFunction(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// A description of what the function does, used by the model to choose when and how to call the function. + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsFunctionToolDefinitionFunction(string description, string name, BinaryData parameters, bool? strict, IDictionary serializedAdditionalRawData) + { + Description = description; + Name = name; + Parameters = parameters; + Strict = strict; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolDefinitionFunction() + { + } + + /// A description of what the function does, used by the model to choose when and how to call the function. + public string Description { get; set; } + /// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + public string Name { get; } + /// + /// Gets or sets the parameters + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Parameters { get; set; } + /// Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](docs/guides/function-calling). + public bool? Strict { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.Serialization.cs new file mode 100644 index 000000000000..f820a0fa7b11 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsFunctionToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolSelection)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsFunctionToolSelection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsFunctionToolSelection(document.RootElement, options); + } + + internal static ChatCompletionsFunctionToolSelection DeserializeChatCompletionsFunctionToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsFunctionToolSelection(name, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsFunctionToolSelection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsFunctionToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsFunctionToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsFunctionToolSelection(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.cs similarity index 65% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.cs index 5a1af0cc4664..419c61a67c34 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/CreateAssistantFileRequest.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsFunctionToolSelection.cs @@ -8,10 +8,10 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - /// The CreateAssistantFileRequest. - internal partial class CreateAssistantFileRequest + /// A tool selection of a specific, named function tool that will limit chat completions to using the named function. + public partial class ChatCompletionsFunctionToolSelection { /// /// Keeps track of any properties unknown to the library. @@ -45,31 +45,31 @@ internal partial class CreateAssistantFileRequest /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The ID of the previously uploaded file to attach. - /// is null. - internal CreateAssistantFileRequest(string fileId) + /// Initializes a new instance of . + /// The name of the function that should be called. + /// is null. + public ChatCompletionsFunctionToolSelection(string name) { - Argument.AssertNotNull(fileId, nameof(fileId)); + Argument.AssertNotNull(name, nameof(name)); - FileId = fileId; + Name = name; } - /// Initializes a new instance of . - /// The ID of the previously uploaded file to attach. + /// Initializes a new instance of . + /// The name of the function that should be called. /// Keeps track of any properties unknown to the library. - internal CreateAssistantFileRequest(string fileId, IDictionary serializedAdditionalRawData) + internal ChatCompletionsFunctionToolSelection(string name, IDictionary serializedAdditionalRawData) { - FileId = fileId; + Name = name; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal CreateAssistantFileRequest() + /// Initializes a new instance of for deserialization. + internal ChatCompletionsFunctionToolSelection() { } - /// The ID of the previously uploaded file to attach. - public string FileId { get; } + /// The name of the function that should be called. + public string Name { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.Serialization.cs new file mode 100644 index 000000000000..13758c30eafa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsJsonResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsJsonResponseFormat)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ChatCompletionsJsonResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsJsonResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsJsonResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsJsonResponseFormat DeserializeChatCompletionsJsonResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsJsonResponseFormat(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsJsonResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsJsonResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsJsonResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsJsonResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.cs new file mode 100644 index 000000000000..f38d98e6fbd6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonResponseFormat.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A response format for Chat Completions that restricts responses to emitting valid JSON objects. + public partial class ChatCompletionsJsonResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + public ChatCompletionsJsonResponseFormat() + { + Type = "json_object"; + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsJsonResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.Serialization.cs new file mode 100644 index 000000000000..4ef9039650c4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsJsonSchemaResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormat)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("json_schema"u8); + writer.WriteObjectValue(JsonSchema, options); + } + + ChatCompletionsJsonSchemaResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsJsonSchemaResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsJsonSchemaResponseFormat DeserializeChatCompletionsJsonSchemaResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("json_schema"u8)) + { + jsonSchema = ChatCompletionsJsonSchemaResponseFormatJsonSchema.DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsJsonSchemaResponseFormat(type, serializedAdditionalRawData, jsonSchema); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsJsonSchemaResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsJsonSchemaResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsJsonSchemaResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsJsonSchemaResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.cs new file mode 100644 index 000000000000..9892e885aba7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormat.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A response format for Chat Completions that restricts responses to emitting JSON that conforms to a provided JSON + /// Schema for Structured Outputs. + /// + public partial class ChatCompletionsJsonSchemaResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + /// + /// is null. + public ChatCompletionsJsonSchemaResponseFormat(ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema) + { + Argument.AssertNotNull(jsonSchema, nameof(jsonSchema)); + + Type = "json_schema"; + JsonSchema = jsonSchema; + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + /// + internal ChatCompletionsJsonSchemaResponseFormat(string type, IDictionary serializedAdditionalRawData, ChatCompletionsJsonSchemaResponseFormatJsonSchema jsonSchema) : base(type, serializedAdditionalRawData) + { + JsonSchema = jsonSchema; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsJsonSchemaResponseFormat() + { + } + + /// Gets the json schema. + public ChatCompletionsJsonSchemaResponseFormatJsonSchema JsonSchema { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.Serialization.cs new file mode 100644 index 000000000000..60504e5e35db --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.Serialization.cs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsJsonSchemaResponseFormatJsonSchema : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Optional.IsDefined(Schema)) + { + writer.WritePropertyName("schema"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Schema); +#else + using (JsonDocument document = JsonDocument.Parse(Schema, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(Strict)) + { + if (Strict != null) + { + writer.WritePropertyName("strict"u8); + writer.WriteBooleanValue(Strict.Value); + } + else + { + writer.WriteNull("strict"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsJsonSchemaResponseFormatJsonSchema IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(document.RootElement, options); + } + + internal static ChatCompletionsJsonSchemaResponseFormatJsonSchema DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string description = default; + string name = default; + BinaryData schema = default; + bool? strict = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("schema"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + schema = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("strict"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + strict = null; + continue; + } + strict = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsJsonSchemaResponseFormatJsonSchema(description, name, schema, strict, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsJsonSchemaResponseFormatJsonSchema IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsJsonSchemaResponseFormatJsonSchema)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsJsonSchemaResponseFormatJsonSchema FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsJsonSchemaResponseFormatJsonSchema(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.cs new file mode 100644 index 000000000000..344920808c8c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsJsonSchemaResponseFormatJsonSchema.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The ChatCompletionsJsonSchemaResponseFormatJsonSchema. + public partial class ChatCompletionsJsonSchemaResponseFormatJsonSchema + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// is null. + public ChatCompletionsJsonSchemaResponseFormatJsonSchema(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// A description of what the response format is for, used by the model to determine how to respond in the format. + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + /// + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsJsonSchemaResponseFormatJsonSchema(string description, string name, BinaryData schema, bool? strict, IDictionary serializedAdditionalRawData) + { + Description = description; + Name = name; + Schema = schema; + Strict = strict; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsJsonSchemaResponseFormatJsonSchema() + { + } + + /// A description of what the response format is for, used by the model to determine how to respond in the format. + public string Description { get; set; } + /// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. + public string Name { get; } + /// + /// Gets or sets the schema + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Schema { get; set; } + /// Whether to enable strict schema adherence when generating the output. If set to true, the model will always follow the exact schema defined in the `schema` field. Only a subset of JSON Schema is supported when `strict` is `true`. To learn more, read the [Structured Outputs guide](/docs/guides/structured-outputs). + public bool? Strict { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.Serialization.cs new file mode 100644 index 000000000000..787d40d07078 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsNamedFunctionToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsNamedFunctionToolSelection)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("function"u8); + writer.WriteObjectValue(Function, options); + } + + ChatCompletionsNamedFunctionToolSelection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsNamedFunctionToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsNamedFunctionToolSelection(document.RootElement, options); + } + + internal static ChatCompletionsNamedFunctionToolSelection DeserializeChatCompletionsNamedFunctionToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatCompletionsFunctionToolSelection function = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("function"u8)) + { + function = ChatCompletionsFunctionToolSelection.DeserializeChatCompletionsFunctionToolSelection(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsNamedFunctionToolSelection(type, serializedAdditionalRawData, function); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedFunctionToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsNamedFunctionToolSelection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsNamedFunctionToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedFunctionToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsNamedFunctionToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsNamedFunctionToolSelection(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.cs new file mode 100644 index 000000000000..2645a6e5ad04 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedFunctionToolSelection.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A tool selection of a specific, named function tool that will limit chat completions to using the named function. + public partial class ChatCompletionsNamedFunctionToolSelection : ChatCompletionsNamedToolSelection + { + /// Initializes a new instance of . + /// The function that should be called. + /// is null. + public ChatCompletionsNamedFunctionToolSelection(ChatCompletionsFunctionToolSelection function) + { + Argument.AssertNotNull(function, nameof(function)); + + Type = "function"; + Function = function; + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + /// The function that should be called. + internal ChatCompletionsNamedFunctionToolSelection(string type, IDictionary serializedAdditionalRawData, ChatCompletionsFunctionToolSelection function) : base(type, serializedAdditionalRawData) + { + Function = function; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsNamedFunctionToolSelection() + { + } + + /// The function that should be called. + public ChatCompletionsFunctionToolSelection Function { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.Serialization.cs new file mode 100644 index 000000000000..038376e047df --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.Serialization.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsNamedToolSelection))] + public partial class ChatCompletionsNamedToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsNamedToolSelection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + + internal static ChatCompletionsNamedToolSelection DeserializeChatCompletionsNamedToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "function": return ChatCompletionsNamedFunctionToolSelection.DeserializeChatCompletionsNamedFunctionToolSelection(element, options); + } + } + return UnknownChatCompletionsNamedToolSelection.DeserializeUnknownChatCompletionsNamedToolSelection(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsNamedToolSelection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsNamedToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.cs new file mode 100644 index 000000000000..b25ed8fab461 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsNamedToolSelection.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of an explicit, named tool selection to use for a chat completions request. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public abstract partial class ChatCompletionsNamedToolSelection + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatCompletionsNamedToolSelection() + { + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsNamedToolSelection(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.Serialization.cs new file mode 100644 index 000000000000..9a9e531cabd7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.Serialization.cs @@ -0,0 +1,752 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("messages"u8); + writer.WriteStartArray(); + foreach (var item in Messages) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsCollectionDefined(Functions)) + { + writer.WritePropertyName("functions"u8); + writer.WriteStartArray(); + foreach (var item in Functions) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FunctionCall)) + { + writer.WritePropertyName("function_call"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(FunctionCall); +#else + using (JsonDocument document = JsonDocument.Parse(FunctionCall, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(MaxTokens)) + { + writer.WritePropertyName("max_tokens"u8); + writer.WriteNumberValue(MaxTokens.Value); + } + if (Optional.IsDefined(MaxCompletionTokens)) + { + writer.WritePropertyName("max_completion_tokens"u8); + writer.WriteNumberValue(MaxCompletionTokens.Value); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsDefined(NucleusSamplingFactor)) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); + } + if (Optional.IsCollectionDefined(TokenSelectionBiases)) + { + writer.WritePropertyName("logit_bias"u8); + writer.WriteStartObject(); + foreach (var item in TokenSelectionBiases) + { + writer.WritePropertyName(item.Key); + writer.WriteNumberValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (Optional.IsDefined(ChoiceCount)) + { + writer.WritePropertyName("n"u8); + writer.WriteNumberValue(ChoiceCount.Value); + } + if (Optional.IsCollectionDefined(StopSequences)) + { + writer.WritePropertyName("stop"u8); + writer.WriteStartArray(); + foreach (var item in StopSequences) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(PresencePenalty)) + { + writer.WritePropertyName("presence_penalty"u8); + writer.WriteNumberValue(PresencePenalty.Value); + } + if (Optional.IsDefined(FrequencyPenalty)) + { + writer.WritePropertyName("frequency_penalty"u8); + writer.WriteNumberValue(FrequencyPenalty.Value); + } + if (Optional.IsDefined(InternalShouldStreamResponse)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(InternalShouldStreamResponse.Value); + } + if (Optional.IsDefined(StreamOptions)) + { + if (StreamOptions != null) + { + writer.WritePropertyName("stream_options"u8); + writer.WriteObjectValue(StreamOptions, options); + } + else + { + writer.WriteNull("stream_options"); + } + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (Optional.IsCollectionDefined(InternalAzureExtensionsDataSources)) + { + writer.WritePropertyName("data_sources"u8); + writer.WriteStartArray(); + foreach (var item in InternalAzureExtensionsDataSources) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Enhancements)) + { + writer.WritePropertyName("enhancements"u8); + writer.WriteObjectValue(Enhancements, options); + } + if (Optional.IsDefined(Seed)) + { + writer.WritePropertyName("seed"u8); + writer.WriteNumberValue(Seed.Value); + } + if (Optional.IsDefined(EnableLogProbabilities)) + { + if (EnableLogProbabilities != null) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteBooleanValue(EnableLogProbabilities.Value); + } + else + { + writer.WriteNull("logprobs"); + } + } + if (Optional.IsDefined(LogProbabilitiesPerToken)) + { + if (LogProbabilitiesPerToken != null) + { + writer.WritePropertyName("top_logprobs"u8); + writer.WriteNumberValue(LogProbabilitiesPerToken.Value); + } + else + { + writer.WriteNull("top_logprobs"); + } + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteObjectValue(ResponseFormat, options); + } + if (Optional.IsCollectionDefined(Tools)) + { + writer.WritePropertyName("tools"u8); + writer.WriteStartArray(); + foreach (var item in Tools) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(ToolChoice)) + { + writer.WritePropertyName("tool_choice"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(ToolChoice); +#else + using (JsonDocument document = JsonDocument.Parse(ToolChoice, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (Optional.IsDefined(ParallelToolCalls)) + { + writer.WritePropertyName("parallel_tool_calls"u8); + writer.WriteBooleanValue(ParallelToolCalls.Value); + } + if (Optional.IsDefined(Store)) + { + writer.WritePropertyName("store"u8); + writer.WriteBooleanValue(Store.Value); + } + if (Optional.IsCollectionDefined(Metadata)) + { + writer.WritePropertyName("metadata"u8); + writer.WriteStartObject(); + foreach (var item in Metadata) + { + writer.WritePropertyName(item.Key); + writer.WriteStringValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(ReasoningEffort)) + { + writer.WritePropertyName("reasoning_effort"u8); + writer.WriteStringValue(ReasoningEffort.Value.ToString()); + } + if (Optional.IsDefined(UserSecurityContext)) + { + writer.WritePropertyName("user_security_context"u8); + writer.WriteObjectValue(UserSecurityContext, options); + } + if (Optional.IsCollectionDefined(Modalities)) + { + writer.WritePropertyName("modalities"u8); + writer.WriteStartArray(); + foreach (var item in Modalities) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Prediction)) + { + writer.WritePropertyName("prediction"u8); + writer.WriteObjectValue(Prediction, options); + } + if (Optional.IsDefined(Audio)) + { + writer.WritePropertyName("audio"u8); + writer.WriteObjectValue(Audio, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsOptions(document.RootElement, options); + } + + internal static ChatCompletionsOptions DeserializeChatCompletionsOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList messages = default; + IList functions = default; + BinaryData functionCall = default; + int? maxTokens = default; + int? maxCompletionTokens = default; + float? temperature = default; + float? topP = default; + IDictionary logitBias = default; + string user = default; + int? n = default; + IList stop = default; + float? presencePenalty = default; + float? frequencyPenalty = default; + bool? stream = default; + ChatCompletionStreamOptions streamOptions = default; + string model = default; + IList dataSources = default; + AzureChatEnhancementConfiguration enhancements = default; + long? seed = default; + bool? logprobs = default; + int? topLogprobs = default; + ChatCompletionsResponseFormat responseFormat = default; + IList tools = default; + BinaryData toolChoice = default; + bool? parallelToolCalls = default; + bool? store = default; + IDictionary metadata = default; + ReasoningEffortValue? reasoningEffort = default; + UserSecurityContext userSecurityContext = default; + IList modalities = default; + PredictionContent prediction = default; + AudioOutputParameters audio = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("messages"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatRequestMessage.DeserializeChatRequestMessage(item, options)); + } + messages = array; + continue; + } + if (property.NameEquals("functions"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(FunctionDefinition.DeserializeFunctionDefinition(item, options)); + } + functions = array; + continue; + } + if (property.NameEquals("function_call"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + functionCall = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("max_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_completion_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxCompletionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("logit_bias"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetInt32()); + } + logitBias = dictionary; + continue; + } + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (property.NameEquals("n"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + n = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("stop"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + stop = array; + continue; + } + if (property.NameEquals("presence_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + presencePenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("frequency_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + frequencyPenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stream_options"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + streamOptions = null; + continue; + } + streamOptions = ChatCompletionStreamOptions.DeserializeChatCompletionStreamOptions(property.Value, options); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("data_sources"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(AzureChatExtensionConfiguration.DeserializeAzureChatExtensionConfiguration(item, options)); + } + dataSources = array; + continue; + } + if (property.NameEquals("enhancements"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + enhancements = AzureChatEnhancementConfiguration.DeserializeAzureChatEnhancementConfiguration(property.Value, options); + continue; + } + if (property.NameEquals("seed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + seed = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + logprobs = null; + continue; + } + logprobs = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("top_logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topLogprobs = null; + continue; + } + topLogprobs = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = ChatCompletionsResponseFormat.DeserializeChatCompletionsResponseFormat(property.Value, options); + continue; + } + if (property.NameEquals("tools"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatCompletionsToolDefinition.DeserializeChatCompletionsToolDefinition(item, options)); + } + tools = array; + continue; + } + if (property.NameEquals("tool_choice"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + toolChoice = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("parallel_tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parallelToolCalls = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("store"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + store = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("metadata"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetString()); + } + metadata = dictionary; + continue; + } + if (property.NameEquals("reasoning_effort"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + reasoningEffort = new ReasoningEffortValue(property.Value.GetString()); + continue; + } + if (property.NameEquals("user_security_context"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + userSecurityContext = UserSecurityContext.DeserializeUserSecurityContext(property.Value, options); + continue; + } + if (property.NameEquals("modalities"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new ChatCompletionModality(item.GetString())); + } + modalities = array; + continue; + } + if (property.NameEquals("prediction"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + prediction = PredictionContent.DeserializePredictionContent(property.Value, options); + continue; + } + if (property.NameEquals("audio"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + audio = AudioOutputParameters.DeserializeAudioOutputParameters(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsOptions( + messages, + functions ?? new ChangeTrackingList(), + functionCall, + maxTokens, + maxCompletionTokens, + temperature, + topP, + logitBias ?? new ChangeTrackingDictionary(), + user, + n, + stop ?? new ChangeTrackingList(), + presencePenalty, + frequencyPenalty, + stream, + streamOptions, + model, + dataSources ?? new ChangeTrackingList(), + enhancements, + seed, + logprobs, + topLogprobs, + responseFormat, + tools ?? new ChangeTrackingList(), + toolChoice, + parallelToolCalls, + store, + metadata ?? new ChangeTrackingDictionary(), + reasoningEffort, + userSecurityContext, + modalities ?? new ChangeTrackingList(), + prediction, + audio, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsOptions)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.cs new file mode 100644 index 000000000000..56f9c921b23b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsOptions.cs @@ -0,0 +1,482 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// The configuration information for a chat completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + public partial class ChatCompletionsOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// The collection of context messages associated with this chat completions request. + /// Typical usage begins with a chat message for the System role that provides instructions for + /// the behavior of the assistant, followed by alternating messages between the User and + /// Assistant roles. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , and . + /// + /// is null. + public ChatCompletionsOptions(IEnumerable messages) + { + Argument.AssertNotNull(messages, nameof(messages)); + + Messages = messages.ToList(); + Functions = new ChangeTrackingList(); + TokenSelectionBiases = new ChangeTrackingDictionary(); + StopSequences = new ChangeTrackingList(); + InternalAzureExtensionsDataSources = new ChangeTrackingList(); + Tools = new ChangeTrackingList(); + Metadata = new ChangeTrackingDictionary(); + Modalities = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// + /// The collection of context messages associated with this chat completions request. + /// Typical usage begins with a chat message for the System role that provides instructions for + /// the behavior of the assistant, followed by alternating messages between the User and + /// Assistant roles. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , and . + /// + /// A list of functions the model may generate JSON inputs for. + /// + /// 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. + /// + /// + /// The maximum number of tokens allowed for the generated answer. By default, the number of tokens the model can return will be (4096 - prompt tokens). + /// + /// This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with o1 series models. + /// + /// An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens. + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + /// + /// 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 max_tokens and stop. + /// + /// A collection of textual sequences that will end completions generation. + /// + /// 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. + /// + /// + /// 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. + /// + /// A value indicating whether chat completions should be streamed for this request. + /// Options for streaming response. Only set this when you set `stream: true`. + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + /// + /// The configuration entries for Azure OpenAI chat extensions that use them. + /// This additional specification is only compatible with Azure OpenAI. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + /// If provided, the configuration options for available Azure OpenAI chat enhancements. + /// + /// 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." + /// + /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. This option is currently not available on the `gpt-4-vision-preview` model. + /// An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + /// + /// An object specifying the format that the model must output. Used to enable JSON mode. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + /// + /// The available tool definitions that the chat completions request can use, including caller-defined functions. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// If specified, the model will configure which of the provided tools it can use for the chat completions response. + /// Whether to enable parallel function calling during tool use. + /// Whether or not to store the output of this chat completion request for use in our model distillation or evaluation products. + /// Developer-defined tags and values used for filtering completions in the stored completions dashboard. + /// + /// This option is only valid for o1 models, + /// + /// Constrains effort on reasoning for reasoning models (see https://platform.openai.com/docs/guides/reasoning). + /// + /// Currently supported values are `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + /// + /// The security context identifies and authenticates users and applications in your multi-tenant AI system, helping security teams investigate and mitigate incidents. + /// + /// Output types that you would like the model to generate for this request. + /// Most models are capable of generating text, which is the default: `["text"]` + /// The `gpt-4o-audio-preview` model can also be used to generate audio. To + /// request that this model generate both text and audio responses, you can + /// use: `["text", "audio"]` + /// + /// + /// Configuration for a Predicted Output, which can greatly improve response times + /// when large parts of the model response are known ahead of time. This is most + /// common when you are regenerating a file with only minor changes to most of the content. + /// + /// + /// Parameters for audio output. Required when audio output is requested + /// with `modalities: ["audio"]` + /// + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsOptions(IList messages, IList functions, BinaryData functionCall, int? maxTokens, int? maxCompletionTokens, float? temperature, float? nucleusSamplingFactor, IDictionary tokenSelectionBiases, string user, int? choiceCount, IList stopSequences, float? presencePenalty, float? frequencyPenalty, bool? internalShouldStreamResponse, ChatCompletionStreamOptions streamOptions, string deploymentName, IList internalAzureExtensionsDataSources, AzureChatEnhancementConfiguration enhancements, long? seed, bool? enableLogProbabilities, int? logProbabilitiesPerToken, ChatCompletionsResponseFormat responseFormat, IList tools, BinaryData toolChoice, bool? parallelToolCalls, bool? store, IDictionary metadata, ReasoningEffortValue? reasoningEffort, UserSecurityContext userSecurityContext, IList modalities, PredictionContent prediction, AudioOutputParameters audio, IDictionary serializedAdditionalRawData) + { + Messages = messages; + Functions = functions; + FunctionCall = functionCall; + MaxTokens = maxTokens; + MaxCompletionTokens = maxCompletionTokens; + Temperature = temperature; + NucleusSamplingFactor = nucleusSamplingFactor; + TokenSelectionBiases = tokenSelectionBiases; + User = user; + ChoiceCount = choiceCount; + StopSequences = stopSequences; + PresencePenalty = presencePenalty; + FrequencyPenalty = frequencyPenalty; + InternalShouldStreamResponse = internalShouldStreamResponse; + StreamOptions = streamOptions; + DeploymentName = deploymentName; + InternalAzureExtensionsDataSources = internalAzureExtensionsDataSources; + Enhancements = enhancements; + Seed = seed; + EnableLogProbabilities = enableLogProbabilities; + LogProbabilitiesPerToken = logProbabilitiesPerToken; + ResponseFormat = responseFormat; + Tools = tools; + ToolChoice = toolChoice; + ParallelToolCalls = parallelToolCalls; + Store = store; + Metadata = metadata; + ReasoningEffort = reasoningEffort; + UserSecurityContext = userSecurityContext; + Modalities = modalities; + Prediction = prediction; + Audio = audio; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsOptions() + { + } + + /// + /// The collection of context messages associated with this chat completions request. + /// Typical usage begins with a chat message for the System role that provides instructions for + /// the behavior of the assistant, followed by alternating messages between the User and + /// Assistant roles. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , and . + /// + public IList Messages { get; } + /// A list of functions the model may generate JSON inputs for. + public IList Functions { get; } + /// + /// 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. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData FunctionCall { get; set; } + /// + /// The maximum number of tokens allowed for the generated answer. By default, the number of tokens the model can return will be (4096 - prompt tokens). + /// + /// This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with o1 series models. + /// + public int? MaxTokens { get; set; } + /// An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens. + public int? MaxCompletionTokens { get; set; } + /// + /// 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. + /// + public float? Temperature { get; set; } + /// + /// 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. + /// + public float? NucleusSamplingFactor { get; set; } + /// + /// 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. + /// + public IDictionary TokenSelectionBiases { get; } + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + public string User { get; set; } + /// + /// 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 max_tokens and stop. + /// + public int? ChoiceCount { get; set; } + /// A collection of textual sequences that will end completions generation. + public IList StopSequences { get; } + /// + /// 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. + /// + public float? PresencePenalty { get; set; } + /// + /// 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. + /// + public float? FrequencyPenalty { get; set; } + /// A value indicating whether chat completions should be streamed for this request. + public bool? InternalShouldStreamResponse { get; set; } + /// Options for streaming response. Only set this when you set `stream: true`. + public ChatCompletionStreamOptions StreamOptions { get; set; } + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + public string DeploymentName { get; set; } + /// + /// The configuration entries for Azure OpenAI chat extensions that use them. + /// This additional specification is only compatible with Azure OpenAI. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , and . + /// + public IList InternalAzureExtensionsDataSources { get; } + /// If provided, the configuration options for available Azure OpenAI chat enhancements. + public AzureChatEnhancementConfiguration Enhancements { get; set; } + /// + /// 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." + /// + public long? Seed { get; set; } + /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`. This option is currently not available on the `gpt-4-vision-preview` model. + public bool? EnableLogProbabilities { get; set; } + /// An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used. + public int? LogProbabilitiesPerToken { get; set; } + /// + /// An object specifying the format that the model must output. Used to enable JSON mode. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public ChatCompletionsResponseFormat ResponseFormat { get; set; } + /// + /// The available tool definitions that the chat completions request can use, including caller-defined functions. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IList Tools { get; } + /// + /// If specified, the model will configure which of the provided tools it can use for the chat completions response. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData ToolChoice { get; set; } + /// Whether to enable parallel function calling during tool use. + public bool? ParallelToolCalls { get; set; } + /// Whether or not to store the output of this chat completion request for use in our model distillation or evaluation products. + public bool? Store { get; set; } + /// Developer-defined tags and values used for filtering completions in the stored completions dashboard. + public IDictionary Metadata { get; } + /// + /// This option is only valid for o1 models, + /// + /// Constrains effort on reasoning for reasoning models (see https://platform.openai.com/docs/guides/reasoning). + /// + /// Currently supported values are `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + /// + public ReasoningEffortValue? ReasoningEffort { get; set; } + /// The security context identifies and authenticates users and applications in your multi-tenant AI system, helping security teams investigate and mitigate incidents. + public UserSecurityContext UserSecurityContext { get; set; } + /// + /// Output types that you would like the model to generate for this request. + /// Most models are capable of generating text, which is the default: `["text"]` + /// The `gpt-4o-audio-preview` model can also be used to generate audio. To + /// request that this model generate both text and audio responses, you can + /// use: `["text", "audio"]` + /// + public IList Modalities { get; } + /// + /// Configuration for a Predicted Output, which can greatly improve response times + /// when large parts of the model response are known ahead of time. This is most + /// common when you are regenerating a file with only minor changes to most of the content. + /// + public PredictionContent Prediction { get; set; } + /// + /// Parameters for audio output. Required when audio output is requested + /// with `modalities: ["audio"]` + /// + public AudioOutputParameters Audio { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.Serialization.cs new file mode 100644 index 000000000000..4b289e19dff3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsResponseFormat))] + public partial class ChatCompletionsResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsResponseFormat DeserializeChatCompletionsResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "json_object": return ChatCompletionsJsonResponseFormat.DeserializeChatCompletionsJsonResponseFormat(element, options); + case "json_schema": return ChatCompletionsJsonSchemaResponseFormat.DeserializeChatCompletionsJsonSchemaResponseFormat(element, options); + case "text": return ChatCompletionsTextResponseFormat.DeserializeChatCompletionsTextResponseFormat(element, options); + } + } + return UnknownChatCompletionsResponseFormat.DeserializeUnknownChatCompletionsResponseFormat(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsResponseFormat(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.cs new file mode 100644 index 000000000000..43211d2ed3cb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsResponseFormat.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a response format configuration usable by Chat Completions. Can be used to enable JSON + /// mode. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , and . + /// + public abstract partial class ChatCompletionsResponseFormat + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatCompletionsResponseFormat() + { + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsResponseFormat(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The discriminated type for the response format. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.Serialization.cs new file mode 100644 index 000000000000..25e9b88480db --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatCompletionsTextResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsTextResponseFormat)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ChatCompletionsTextResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsTextResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsTextResponseFormat(document.RootElement, options); + } + + internal static ChatCompletionsTextResponseFormat DeserializeChatCompletionsTextResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatCompletionsTextResponseFormat(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsTextResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsTextResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsTextResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsTextResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatCompletionsTextResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsTextResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.cs new file mode 100644 index 000000000000..d1bf93c195ba --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsTextResponseFormat.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class ChatCompletionsTextResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + public ChatCompletionsTextResponseFormat() + { + Type = "text"; + } + + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsTextResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.Serialization.cs new file mode 100644 index 000000000000..f8dc61732c4f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.Serialization.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsToolCall))] + public partial class ChatCompletionsToolCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsToolCall(document.RootElement, options); + } + + internal static ChatCompletionsToolCall DeserializeChatCompletionsToolCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "function": return ChatCompletionsFunctionToolCall.DeserializeChatCompletionsFunctionToolCall(element, options); + } + } + return UnknownChatCompletionsToolCall.DeserializeUnknownChatCompletionsToolCall(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsToolCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsToolCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsToolCall(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.cs new file mode 100644 index 000000000000..a6de3a467520 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolCall.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a tool call that must be resolved in a subsequent request to perform the requested + /// chat completion. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public abstract partial class ChatCompletionsToolCall + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the tool call. + /// is null. + protected ChatCompletionsToolCall(string id) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + } + + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsToolCall(string type, string id, IDictionary serializedAdditionalRawData) + { + Type = type; + Id = id; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatCompletionsToolCall() + { + } + + /// The object type. + internal string Type { get; set; } + /// The ID of the tool call. + public string Id { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.Serialization.cs new file mode 100644 index 000000000000..ba4e61cbcf83 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.Serialization.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatCompletionsToolDefinition))] + public partial class ChatCompletionsToolDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatCompletionsToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + + internal static ChatCompletionsToolDefinition DeserializeChatCompletionsToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "function": return ChatCompletionsFunctionToolDefinition.DeserializeChatCompletionsFunctionToolDefinition(element, options); + } + } + return UnknownChatCompletionsToolDefinition.DeserializeUnknownChatCompletionsToolDefinition(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatCompletionsToolDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsToolDefinition(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.cs new file mode 100644 index 000000000000..712c79c1aeb9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolDefinition.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a tool that can be used by the model to improve a chat completions response. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public abstract partial class ChatCompletionsToolDefinition + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatCompletionsToolDefinition() + { + } + + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal ChatCompletionsToolDefinition(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolSelectionPreset.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolSelectionPreset.cs new file mode 100644 index 000000000000..9916c3d6a74b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatCompletionsToolSelectionPreset.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Represents a generic policy for how a chat completions tool may be selected. + public readonly partial struct ChatCompletionsToolSelectionPreset : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatCompletionsToolSelectionPreset(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string NoneValue = "none"; + private const string RequiredValue = "required"; + + /// + /// Specifies that the model may either use any of the tools provided in this chat completions request or + /// instead return a standard chat completions response as if no tools were provided. + /// + public static ChatCompletionsToolSelectionPreset Auto { get; } = new ChatCompletionsToolSelectionPreset(AutoValue); + /// + /// Specifies that the model should not respond with a tool call and should instead provide a standard chat + /// completions response. Response content may still be influenced by the provided tool definitions. + /// + public static ChatCompletionsToolSelectionPreset None { get; } = new ChatCompletionsToolSelectionPreset(NoneValue); + /// Specifies that the model must call one or more tools. + public static ChatCompletionsToolSelectionPreset Required { get; } = new ChatCompletionsToolSelectionPreset(RequiredValue); + /// Determines if two values are the same. + public static bool operator ==(ChatCompletionsToolSelectionPreset left, ChatCompletionsToolSelectionPreset right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatCompletionsToolSelectionPreset left, ChatCompletionsToolSelectionPreset right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ChatCompletionsToolSelectionPreset(string value) => new ChatCompletionsToolSelectionPreset(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatCompletionsToolSelectionPreset other && Equals(other); + /// + public bool Equals(ChatCompletionsToolSelectionPreset other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.Serialization.cs new file mode 100644 index 000000000000..c26e07179fce --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageAudioContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageAudioContentItem)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("input_audio"u8); + writer.WriteObjectValue(InputAudio, options); + } + + ChatMessageAudioContentItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageAudioContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageAudioContentItem(document.RootElement, options); + } + + internal static ChatMessageAudioContentItem DeserializeChatMessageAudioContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + InputAudioContent inputAudio = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("input_audio"u8)) + { + inputAudio = InputAudioContent.DeserializeInputAudioContent(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageAudioContentItem(type, serializedAdditionalRawData, inputAudio); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatMessageAudioContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageAudioContentItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageAudioContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageAudioContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatMessageAudioContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageAudioContentItem(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.cs new file mode 100644 index 000000000000..e6a2e53315b7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageAudioContentItem.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing audio data. + public partial class ChatMessageAudioContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// The audio data. + /// is null. + public ChatMessageAudioContentItem(InputAudioContent inputAudio) + { + Argument.AssertNotNull(inputAudio, nameof(inputAudio)); + + Type = "input_audio"; + InputAudio = inputAudio; + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + /// The audio data. + internal ChatMessageAudioContentItem(string type, IDictionary serializedAdditionalRawData, InputAudioContent inputAudio) : base(type, serializedAdditionalRawData) + { + InputAudio = inputAudio; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageAudioContentItem() + { + } + + /// The audio data. + public InputAudioContent InputAudio { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.Serialization.cs new file mode 100644 index 000000000000..ed88ebb8feb9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.Serialization.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatMessageContentItem))] + public partial class ChatMessageContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatMessageContentItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageContentItem(document.RootElement, options); + } + + internal static ChatMessageContentItem DeserializeChatMessageContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "image_url": return ChatMessageImageContentItem.DeserializeChatMessageImageContentItem(element, options); + case "input_audio": return ChatMessageAudioContentItem.DeserializeChatMessageAudioContentItem(element, options); + case "refusal": return ChatMessageRefusalContentItem.DeserializeChatMessageRefusalContentItem(element, options); + case "text": return ChatMessageTextContentItem.DeserializeChatMessageTextContentItem(element, options); + } + } + return UnknownChatMessageContentItem.DeserializeUnknownChatMessageContentItem(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageContentItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatMessageContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageContentItem(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.cs new file mode 100644 index 000000000000..f3b8ff8a63ab --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageContentItem.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a structured content item within a chat message. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public abstract partial class ChatMessageContentItem + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatMessageContentItem() + { + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + internal ChatMessageContentItem(string type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The discriminated object type. + internal string Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.Serialization.cs new file mode 100644 index 000000000000..0d58aa2c83d6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageImageContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageImageContentItem)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("image_url"u8); + writer.WriteObjectValue(ImageUrl, options); + } + + ChatMessageImageContentItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageImageContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageImageContentItem(document.RootElement, options); + } + + internal static ChatMessageImageContentItem DeserializeChatMessageImageContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatMessageImageUrl imageUrl = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("image_url"u8)) + { + imageUrl = ChatMessageImageUrl.DeserializeChatMessageImageUrl(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageImageContentItem(type, serializedAdditionalRawData, imageUrl); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatMessageImageContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageImageContentItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageImageContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageImageContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatMessageImageContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageImageContentItem(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.cs new file mode 100644 index 000000000000..69aaa3ec3cea --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageContentItem.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing an image reference. + public partial class ChatMessageImageContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + /// is null. + public ChatMessageImageContentItem(ChatMessageImageUrl imageUrl) + { + Argument.AssertNotNull(imageUrl, nameof(imageUrl)); + + Type = "image_url"; + ImageUrl = imageUrl; + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + internal ChatMessageImageContentItem(string type, IDictionary serializedAdditionalRawData, ChatMessageImageUrl imageUrl) : base(type, serializedAdditionalRawData) + { + ImageUrl = imageUrl; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageImageContentItem() + { + } + + /// An internet location, which must be accessible to the model,from which the image may be retrieved. + public ChatMessageImageUrl ImageUrl { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageDetailLevel.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageDetailLevel.cs new file mode 100644 index 000000000000..bc0649288b24 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageDetailLevel.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// A representation of the possible image detail levels for image-based chat completions message content. + public readonly partial struct ChatMessageImageDetailLevel : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatMessageImageDetailLevel(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string LowValue = "low"; + private const string HighValue = "high"; + + /// Specifies that the model should determine which detail level to apply using heuristics like image size. + public static ChatMessageImageDetailLevel Auto { get; } = new ChatMessageImageDetailLevel(AutoValue); + /// + /// Specifies that image evaluation should be constrained to the 'low-res' model that may be faster and consume fewer + /// tokens but may also be less accurate for highly detailed images. + /// + public static ChatMessageImageDetailLevel Low { get; } = new ChatMessageImageDetailLevel(LowValue); + /// + /// Specifies that image evaluation should enable the 'high-res' model that may be more accurate for highly detailed + /// images but may also be slower and consume more tokens. + /// + public static ChatMessageImageDetailLevel High { get; } = new ChatMessageImageDetailLevel(HighValue); + /// Determines if two values are the same. + public static bool operator ==(ChatMessageImageDetailLevel left, ChatMessageImageDetailLevel right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatMessageImageDetailLevel left, ChatMessageImageDetailLevel right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ChatMessageImageDetailLevel(string value) => new ChatMessageImageDetailLevel(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatMessageImageDetailLevel other && Equals(other); + /// + public bool Equals(ChatMessageImageDetailLevel other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.Serialization.cs new file mode 100644 index 000000000000..c6c461ff31a6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageImageUrl : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageImageUrl)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("url"u8); + writer.WriteStringValue(Url.AbsoluteUri); + if (Optional.IsDefined(Detail)) + { + writer.WritePropertyName("detail"u8); + writer.WriteStringValue(Detail.Value.ToString()); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatMessageImageUrl IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageImageUrl)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageImageUrl(document.RootElement, options); + } + + internal static ChatMessageImageUrl DeserializeChatMessageImageUrl(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Uri url = default; + ChatMessageImageDetailLevel? detail = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("url"u8)) + { + url = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("detail"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + detail = new ChatMessageImageDetailLevel(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageImageUrl(url, detail, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatMessageImageUrl)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageImageUrl IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageImageUrl(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageImageUrl)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatMessageImageUrl FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageImageUrl(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.cs similarity index 51% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.cs index 972c14733528..ccccaecc34cb 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageImageUrl.cs @@ -7,12 +7,11 @@ using System; using System.Collections.Generic; -using System.IO; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI { - /// Request of liveness with verify session creation. - internal partial class CreateLivenessWithVerifySessionMultipartContent + /// An internet location from which the model may retrieve an image. + public partial class ChatMessageImageUrl { /// /// Keeps track of any properties unknown to the library. @@ -46,38 +45,41 @@ internal partial class CreateLivenessWithVerifySessionMultipartContent /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . - /// The parameters for creating session. - /// The image stream for verify. Content-Disposition header field for this part must have filename. - /// or is null. - public CreateLivenessWithVerifySessionMultipartContent(CreateLivenessWithVerifySessionContent parameters, Stream verifyImage) + /// Initializes a new instance of . + /// The URL of the image. + /// is null. + public ChatMessageImageUrl(Uri url) { - Argument.AssertNotNull(parameters, nameof(parameters)); - Argument.AssertNotNull(verifyImage, nameof(verifyImage)); + Argument.AssertNotNull(url, nameof(url)); - Parameters = parameters; - VerifyImage = verifyImage; + Url = url; } - /// Initializes a new instance of . - /// The parameters for creating session. - /// The image stream for verify. Content-Disposition header field for this part must have filename. + /// Initializes a new instance of . + /// The URL of the image. + /// + /// The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and + /// accuracy. + /// /// Keeps track of any properties unknown to the library. - internal CreateLivenessWithVerifySessionMultipartContent(CreateLivenessWithVerifySessionContent parameters, Stream verifyImage, IDictionary serializedAdditionalRawData) + internal ChatMessageImageUrl(Uri url, ChatMessageImageDetailLevel? detail, IDictionary serializedAdditionalRawData) { - Parameters = parameters; - VerifyImage = verifyImage; + Url = url; + Detail = detail; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal CreateLivenessWithVerifySessionMultipartContent() + /// Initializes a new instance of for deserialization. + internal ChatMessageImageUrl() { } - /// The parameters for creating session. - public CreateLivenessWithVerifySessionContent Parameters { get; } - /// The image stream for verify. Content-Disposition header field for this part must have filename. - public Stream VerifyImage { get; } + /// The URL of the image. + public Uri Url { get; } + /// + /// The evaluation quality setting to use, which controls relative prioritization of speed, token consumption, and + /// accuracy. + /// + public ChatMessageImageDetailLevel? Detail { get; set; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.Serialization.cs new file mode 100644 index 000000000000..ecfd5fdb0a56 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageRefusalContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageRefusalContentItem)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + + ChatMessageRefusalContentItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageRefusalContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageRefusalContentItem(document.RootElement, options); + } + + internal static ChatMessageRefusalContentItem DeserializeChatMessageRefusalContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string refusal = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("refusal"u8)) + { + refusal = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageRefusalContentItem(type, serializedAdditionalRawData, refusal); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatMessageRefusalContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageRefusalContentItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageRefusalContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageRefusalContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatMessageRefusalContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageRefusalContentItem(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.cs new file mode 100644 index 000000000000..676b07fb5c85 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageRefusalContentItem.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing model refusal information for a structured outputs request. + public partial class ChatMessageRefusalContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// The refusal message. + /// is null. + public ChatMessageRefusalContentItem(string refusal) + { + Argument.AssertNotNull(refusal, nameof(refusal)); + + Type = "refusal"; + Refusal = refusal; + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + /// The refusal message. + internal ChatMessageRefusalContentItem(string type, IDictionary serializedAdditionalRawData, string refusal) : base(type, serializedAdditionalRawData) + { + Refusal = refusal; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageRefusalContentItem() + { + } + + /// The refusal message. + public string Refusal { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.Serialization.cs new file mode 100644 index 000000000000..bf73ffeeaec1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatMessageTextContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + } + + ChatMessageTextContentItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageTextContentItem(document.RootElement, options); + } + + internal static ChatMessageTextContentItem DeserializeChatMessageTextContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + string type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatMessageTextContentItem(type, serializedAdditionalRawData, text); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageTextContentItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageTextContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageTextContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatMessageTextContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageTextContentItem(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.cs new file mode 100644 index 000000000000..46f0eb167d08 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatMessageTextContentItem.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing plain text. + public partial class ChatMessageTextContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// The content of the message. + /// is null. + public ChatMessageTextContentItem(string text) + { + Argument.AssertNotNull(text, nameof(text)); + + Type = "text"; + Text = text; + } + + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + /// The content of the message. + internal ChatMessageTextContentItem(string type, IDictionary serializedAdditionalRawData, string text) : base(type, serializedAdditionalRawData) + { + Text = text; + } + + /// Initializes a new instance of for deserialization. + internal ChatMessageTextContentItem() + { + } + + /// The content of the message. + public string Text { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.Serialization.cs new file mode 100644 index 000000000000..ac65d65f68d3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.Serialization.cs @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestAssistantMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestAssistantMessage)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Content != null) + { + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("content"); + } + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + if (Optional.IsCollectionDefined(ToolCalls)) + { + writer.WritePropertyName("tool_calls"u8); + writer.WriteStartArray(); + foreach (var item in ToolCalls) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FunctionCall)) + { + writer.WritePropertyName("function_call"u8); + writer.WriteObjectValue(FunctionCall, options); + } + if (Optional.IsDefined(Refusal)) + { + if (Refusal != null) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + else + { + writer.WriteNull("refusal"); + } + } + } + + ChatRequestAssistantMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestAssistantMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestAssistantMessage(document.RootElement, options); + } + + internal static ChatRequestAssistantMessage DeserializeChatRequestAssistantMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string name = default; + IList toolCalls = default; + FunctionCall functionCall = default; + string refusal = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatCompletionsToolCall.DeserializeChatCompletionsToolCall(item, options)); + } + toolCalls = array; + continue; + } + if (property.NameEquals("function_call"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + functionCall = FunctionCall.DeserializeFunctionCall(property.Value, options); + continue; + } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = null; + continue; + } + refusal = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestAssistantMessage( + role, + serializedAdditionalRawData, + content, + name, + toolCalls ?? new ChangeTrackingList(), + functionCall, + refusal); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestAssistantMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestAssistantMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestAssistantMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestAssistantMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestAssistantMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestAssistantMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.cs new file mode 100644 index 000000000000..581014adfeed --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestAssistantMessage.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing response or action from the assistant. + public partial class ChatRequestAssistantMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The content of the message. + public ChatRequestAssistantMessage(BinaryData content) + { + Role = ChatRole.Assistant; + Content = content; + ToolCalls = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The content of the message. + /// An optional name for the participant. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// 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. + /// + /// The refusal message by the assistant. + internal ChatRequestAssistantMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string name, IList toolCalls, FunctionCall functionCall, string refusal) : base(role, serializedAdditionalRawData) + { + Content = content; + Name = name; + ToolCalls = toolCalls; + FunctionCall = functionCall; + Refusal = refusal; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestAssistantMessage() + { + } + + /// + /// The content of the message. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// An optional name for the participant. + public string Name { get; set; } + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IList ToolCalls { get; } + /// + /// 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. + /// + public FunctionCall FunctionCall { get; set; } + /// The refusal message by the assistant. + public string Refusal { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.Serialization.cs new file mode 100644 index 000000000000..e4c580b41428 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestDeveloperMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestDeveloperMessage)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + } + + ChatRequestDeveloperMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestDeveloperMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestDeveloperMessage(document.RootElement, options); + } + + internal static ChatRequestDeveloperMessage DeserializeChatRequestDeveloperMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string name = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestDeveloperMessage(role, serializedAdditionalRawData, content, name); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestDeveloperMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestDeveloperMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestDeveloperMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestDeveloperMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestDeveloperMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestDeveloperMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.cs new file mode 100644 index 000000000000..14262c23f2b4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestDeveloperMessage.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// Developer-provided instructions that the model should follow, regardless of messages sent by the user. + /// With o1 models and newer, `developer` messages replace the previous `system` messages." + /// + public partial class ChatRequestDeveloperMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// An array of content parts with a defined type. For developer messages, only type `text` is supported. + /// is null. + public ChatRequestDeveloperMessage(BinaryData content) + { + Argument.AssertNotNull(content, nameof(content)); + + Role = ChatRole.Developer; + Content = content; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// An array of content parts with a defined type. For developer messages, only type `text` is supported. + /// An optional name for the participant. Provides the model information to differentiate between participants of the same role. + internal ChatRequestDeveloperMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string name) : base(role, serializedAdditionalRawData) + { + Content = content; + Name = name; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestDeveloperMessage() + { + } + + /// + /// An array of content parts with a defined type. For developer messages, only type `text` is supported. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// An optional name for the participant. Provides the model information to differentiate between participants of the same role. + public string Name { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.Serialization.cs new file mode 100644 index 000000000000..131ffafbcb85 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.Serialization.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestFunctionMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestFunctionMessage)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Content != null) + { + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + } + else + { + writer.WriteNull("content"); + } + } + + ChatRequestFunctionMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestFunctionMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestFunctionMessage(document.RootElement, options); + } + + internal static ChatRequestFunctionMessage DeserializeChatRequestFunctionMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string content = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestFunctionMessage(role, serializedAdditionalRawData, name, content); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestFunctionMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestFunctionMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestFunctionMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestFunctionMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestFunctionMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestFunctionMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.cs new file mode 100644 index 000000000000..a4588fc56d21 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestFunctionMessage.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing requested output from a configured function. + public partial class ChatRequestFunctionMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The name of the function that was called to produce output. + /// The output of the function as requested by the function call. + /// is null. + public ChatRequestFunctionMessage(string name, string content) + { + Argument.AssertNotNull(name, nameof(name)); + + Role = ChatRole.Function; + Name = name; + Content = content; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The name of the function that was called to produce output. + /// The output of the function as requested by the function call. + internal ChatRequestFunctionMessage(ChatRole role, IDictionary serializedAdditionalRawData, string name, string content) : base(role, serializedAdditionalRawData) + { + Name = name; + Content = content; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestFunctionMessage() + { + } + + /// The name of the function that was called to produce output. + public string Name { get; } + /// The output of the function as requested by the function call. + public string Content { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.Serialization.cs new file mode 100644 index 000000000000..af4a45810d27 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.Serialization.cs @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownChatRequestMessage))] + public partial class ChatRequestMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatRequestMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestMessage(document.RootElement, options); + } + + internal static ChatRequestMessage DeserializeChatRequestMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("role", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "assistant": return ChatRequestAssistantMessage.DeserializeChatRequestAssistantMessage(element, options); + case "developer": return ChatRequestDeveloperMessage.DeserializeChatRequestDeveloperMessage(element, options); + case "function": return ChatRequestFunctionMessage.DeserializeChatRequestFunctionMessage(element, options); + case "system": return ChatRequestSystemMessage.DeserializeChatRequestSystemMessage(element, options); + case "tool": return ChatRequestToolMessage.DeserializeChatRequestToolMessage(element, options); + case "user": return ChatRequestUserMessage.DeserializeChatRequestUserMessage(element, options); + } + } + return UnknownChatRequestMessage.DeserializeUnknownChatRequestMessage(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatRequestMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestMessage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.cs new file mode 100644 index 000000000000..4dc52154e9cc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestMessage.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a chat message as provided in a request. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , and . + /// + public abstract partial class ChatRequestMessage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected ChatRequestMessage() + { + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + internal ChatRequestMessage(ChatRole role, IDictionary serializedAdditionalRawData) + { + Role = role; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The chat role associated with this message. + internal ChatRole Role { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.Serialization.cs new file mode 100644 index 000000000000..ff8689c21d31 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestSystemMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestSystemMessage)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + } + + ChatRequestSystemMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestSystemMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestSystemMessage(document.RootElement, options); + } + + internal static ChatRequestSystemMessage DeserializeChatRequestSystemMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string name = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestSystemMessage(role, serializedAdditionalRawData, content, name); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestSystemMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestSystemMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestSystemMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestSystemMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestSystemMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestSystemMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.cs new file mode 100644 index 000000000000..388061a2d04a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestSystemMessage.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A request chat message containing system instructions that influence how the model will generate a chat completions + /// response. + /// + public partial class ChatRequestSystemMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The contents of the system message. + /// is null. + public ChatRequestSystemMessage(BinaryData content) + { + Argument.AssertNotNull(content, nameof(content)); + + Role = ChatRole.System; + Content = content; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The contents of the system message. + /// An optional name for the participant. + internal ChatRequestSystemMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string name) : base(role, serializedAdditionalRawData) + { + Content = content; + Name = name; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestSystemMessage() + { + } + + /// + /// The contents of the system message. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// An optional name for the participant. + public string Name { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.Serialization.cs new file mode 100644 index 000000000000..37825267205a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.Serialization.cs @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestToolMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestToolMessage)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + if (Content != null) + { + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + else + { + writer.WriteNull("content"); + } + writer.WritePropertyName("tool_call_id"u8); + writer.WriteStringValue(ToolCallId); + } + + ChatRequestToolMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestToolMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestToolMessage(document.RootElement, options); + } + + internal static ChatRequestToolMessage DeserializeChatRequestToolMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string toolCallId = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("tool_call_id"u8)) + { + toolCallId = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestToolMessage(role, serializedAdditionalRawData, content, toolCallId); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestToolMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestToolMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestToolMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestToolMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestToolMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestToolMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.cs new file mode 100644 index 000000000000..62ea4297b93a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestToolMessage.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing requested output from a configured tool. + public partial class ChatRequestToolMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The content of the message. + /// The ID of the tool call resolved by the provided content. + /// is null. + public ChatRequestToolMessage(BinaryData content, string toolCallId) + { + Argument.AssertNotNull(toolCallId, nameof(toolCallId)); + + Role = ChatRole.Tool; + Content = content; + ToolCallId = toolCallId; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The content of the message. + /// The ID of the tool call resolved by the provided content. + internal ChatRequestToolMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string toolCallId) : base(role, serializedAdditionalRawData) + { + Content = content; + ToolCallId = toolCallId; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestToolMessage() + { + } + + /// + /// The content of the message. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// The ID of the tool call resolved by the provided content. + public string ToolCallId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.Serialization.cs new file mode 100644 index 000000000000..f2b8d66b67c6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.Serialization.cs @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatRequestUserMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestUserMessage)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (Optional.IsDefined(Name)) + { + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + } + } + + ChatRequestUserMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestUserMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestUserMessage(document.RootElement, options); + } + + internal static ChatRequestUserMessage DeserializeChatRequestUserMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + BinaryData content = default; + string name = default; + ChatRole role = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content"u8)) + { + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatRequestUserMessage(role, serializedAdditionalRawData, content, name); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestUserMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestUserMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestUserMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestUserMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ChatRequestUserMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestUserMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.cs new file mode 100644 index 000000000000..51d233de3db8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRequestUserMessage.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A request chat message representing user input to the assistant. + public partial class ChatRequestUserMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The contents of the user message, with available input types varying by selected model. + /// is null. + public ChatRequestUserMessage(BinaryData content) + { + Argument.AssertNotNull(content, nameof(content)); + + Role = ChatRole.User; + Content = content; + } + + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + /// The contents of the user message, with available input types varying by selected model. + /// An optional name for the participant. + internal ChatRequestUserMessage(ChatRole role, IDictionary serializedAdditionalRawData, BinaryData content, string name) : base(role, serializedAdditionalRawData) + { + Content = content; + Name = name; + } + + /// Initializes a new instance of for deserialization. + internal ChatRequestUserMessage() + { + } + + /// + /// The contents of the user message, with available input types varying by selected model. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + /// An optional name for the participant. + public string Name { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.Serialization.cs new file mode 100644 index 000000000000..fb94828684a4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.Serialization.cs @@ -0,0 +1,260 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatResponseMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatResponseMessage)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("role"u8); + writer.WriteStringValue(Role.ToString()); + if (Refusal != null) + { + writer.WritePropertyName("refusal"u8); + writer.WriteStringValue(Refusal); + } + else + { + writer.WriteNull("refusal"); + } + if (Content != null) + { + writer.WritePropertyName("content"u8); + writer.WriteStringValue(Content); + } + else + { + writer.WriteNull("content"); + } + if (Optional.IsCollectionDefined(ToolCalls)) + { + writer.WritePropertyName("tool_calls"u8); + writer.WriteStartArray(); + foreach (var item in ToolCalls) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FunctionCall)) + { + writer.WritePropertyName("function_call"u8); + writer.WriteObjectValue(FunctionCall, options); + } + if (Optional.IsDefined(Audio)) + { + writer.WritePropertyName("audio"u8); + writer.WriteObjectValue(Audio, options); + } + if (Optional.IsDefined(AzureExtensionsContext)) + { + writer.WritePropertyName("context"u8); + writer.WriteObjectValue(AzureExtensionsContext, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatResponseMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatResponseMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatResponseMessage(document.RootElement, options); + } + + internal static ChatResponseMessage DeserializeChatResponseMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatRole role = default; + string refusal = default; + string content = default; + IReadOnlyList toolCalls = default; + FunctionCall functionCall = default; + AudioResponseData audio = default; + AzureChatExtensionsMessageContext context = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (property.NameEquals("refusal"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + refusal = null; + continue; + } + refusal = property.Value.GetString(); + continue; + } + if (property.NameEquals("content"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + content = null; + continue; + } + content = property.Value.GetString(); + continue; + } + if (property.NameEquals("tool_calls"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatCompletionsToolCall.DeserializeChatCompletionsToolCall(item, options)); + } + toolCalls = array; + continue; + } + if (property.NameEquals("function_call"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + functionCall = FunctionCall.DeserializeFunctionCall(property.Value, options); + continue; + } + if (property.NameEquals("audio"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + audio = AudioResponseData.DeserializeAudioResponseData(property.Value, options); + continue; + } + if (property.NameEquals("context"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + context = AzureChatExtensionsMessageContext.DeserializeAzureChatExtensionsMessageContext(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatResponseMessage( + role, + refusal, + content, + toolCalls ?? new ChangeTrackingList(), + functionCall, + audio, + context, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatResponseMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatResponseMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatResponseMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatResponseMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatResponseMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatResponseMessage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.cs new file mode 100644 index 000000000000..971d6a2ae062 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatResponseMessage.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of a chat message as received in a response. + public partial class ChatResponseMessage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The chat role associated with the message. + /// The refusal message generated by the model. + /// The content of the message. + internal ChatResponseMessage(ChatRole role, string refusal, string content) + { + Role = role; + Refusal = refusal; + Content = content; + ToolCalls = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The chat role associated with the message. + /// The refusal message generated by the model. + /// The content of the message. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + /// + /// 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. + /// + /// + /// If the audio output modality is requested, this object contains data + /// about the audio response from the model. + /// + /// + /// If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those + /// extensions while processing the chat completions request. + /// + /// Keeps track of any properties unknown to the library. + internal ChatResponseMessage(ChatRole role, string refusal, string content, IReadOnlyList toolCalls, FunctionCall functionCall, AudioResponseData audio, AzureChatExtensionsMessageContext azureExtensionsContext, IDictionary serializedAdditionalRawData) + { + Role = role; + Refusal = refusal; + Content = content; + ToolCalls = toolCalls; + FunctionCall = functionCall; + Audio = audio; + AzureExtensionsContext = azureExtensionsContext; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatResponseMessage() + { + } + + /// The chat role associated with the message. + public ChatRole Role { get; } + /// The refusal message generated by the model. + public string Refusal { get; } + /// The content of the message. + public string Content { get; } + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include . + /// + public IReadOnlyList ToolCalls { get; } + /// + /// 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. + /// + public FunctionCall FunctionCall { get; } + /// + /// If the audio output modality is requested, this object contains data + /// about the audio response from the model. + /// + public AudioResponseData Audio { get; } + /// + /// If Azure OpenAI chat extensions are configured, this array represents the incremental steps performed by those + /// extensions while processing the chat completions request. + /// + public AzureChatExtensionsMessageContext AzureExtensionsContext { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRole.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRole.cs new file mode 100644 index 000000000000..ba044a6b3de5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatRole.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// A description of the intended purpose of a message within a chat completions interaction. + public readonly partial struct ChatRole : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ChatRole(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SystemValue = "system"; + private const string AssistantValue = "assistant"; + private const string UserValue = "user"; + private const string FunctionValue = "function"; + private const string ToolValue = "tool"; + private const string DeveloperValue = "developer"; + + /// The role that instructs or sets the behavior of the assistant. + public static ChatRole System { get; } = new ChatRole(SystemValue); + /// The role that provides responses to system-instructed, user-prompted input. + public static ChatRole Assistant { get; } = new ChatRole(AssistantValue); + /// The role that provides input for chat completions. + public static ChatRole User { get; } = new ChatRole(UserValue); + /// The role that provides function results for chat completions. + public static ChatRole Function { get; } = new ChatRole(FunctionValue); + /// The role that represents extension tool activity within a chat completions operation. + public static ChatRole Tool { get; } = new ChatRole(ToolValue); + /// The role that provides instructions that the model should follow. + public static ChatRole Developer { get; } = new ChatRole(DeveloperValue); + /// Determines if two values are the same. + public static bool operator ==(ChatRole left, ChatRole right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ChatRole left, ChatRole right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ChatRole(string value) => new ChatRole(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ChatRole other && Equals(other); + /// + public bool Equals(ChatRole other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.Serialization.cs new file mode 100644 index 000000000000..d433ea111106 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.Serialization.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatTokenLogProbabilityInfo : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityInfo)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("token"u8); + writer.WriteStringValue(Token); + writer.WritePropertyName("logprob"u8); + writer.WriteNumberValue(LogProbability); + if (Utf8ByteValues != null && Optional.IsCollectionDefined(Utf8ByteValues)) + { + writer.WritePropertyName("bytes"u8); + writer.WriteStartArray(); + foreach (var item in Utf8ByteValues) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("bytes"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatTokenLogProbabilityInfo IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityInfo)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatTokenLogProbabilityInfo(document.RootElement, options); + } + + internal static ChatTokenLogProbabilityInfo DeserializeChatTokenLogProbabilityInfo(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string token = default; + float logprob = default; + IReadOnlyList bytes = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("token"u8)) + { + token = property.Value.GetString(); + continue; + } + if (property.NameEquals("logprob"u8)) + { + logprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + bytes = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + bytes = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatTokenLogProbabilityInfo(token, logprob, bytes, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityInfo)} does not support writing '{options.Format}' format."); + } + } + + ChatTokenLogProbabilityInfo IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatTokenLogProbabilityInfo(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityInfo)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatTokenLogProbabilityInfo FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatTokenLogProbabilityInfo(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.cs new file mode 100644 index 000000000000..7583c16e09ac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityInfo.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A representation of the log probability information for a single message content token. + public partial class ChatTokenLogProbabilityInfo + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// is null. + internal ChatTokenLogProbabilityInfo(string token, float logProbability, IEnumerable utf8ByteValues) + { + Argument.AssertNotNull(token, nameof(token)); + + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues?.ToList(); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// Keeps track of any properties unknown to the library. + internal ChatTokenLogProbabilityInfo(string token, float logProbability, IReadOnlyList utf8ByteValues, IDictionary serializedAdditionalRawData) + { + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatTokenLogProbabilityInfo() + { + } + + /// The message content token. + public string Token { get; } + /// The log probability of the message content token. + public float LogProbability { get; } + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + public IReadOnlyList Utf8ByteValues { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.Serialization.cs new file mode 100644 index 000000000000..c042226e0873 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.Serialization.cs @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ChatTokenLogProbabilityResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("token"u8); + writer.WriteStringValue(Token); + writer.WritePropertyName("logprob"u8); + writer.WriteNumberValue(LogProbability); + if (Utf8ByteValues != null && Optional.IsCollectionDefined(Utf8ByteValues)) + { + writer.WritePropertyName("bytes"u8); + writer.WriteStartArray(); + foreach (var item in Utf8ByteValues) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("bytes"); + } + if (TopLogProbabilityEntries != null && Optional.IsCollectionDefined(TopLogProbabilityEntries)) + { + writer.WritePropertyName("top_logprobs"u8); + writer.WriteStartArray(); + foreach (var item in TopLogProbabilityEntries) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + else + { + writer.WriteNull("top_logprobs"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ChatTokenLogProbabilityResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatTokenLogProbabilityResult(document.RootElement, options); + } + + internal static ChatTokenLogProbabilityResult DeserializeChatTokenLogProbabilityResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string token = default; + float logprob = default; + IReadOnlyList bytes = default; + IReadOnlyList topLogprobs = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("token"u8)) + { + token = property.Value.GetString(); + continue; + } + if (property.NameEquals("logprob"u8)) + { + logprob = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + bytes = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + bytes = array; + continue; + } + if (property.NameEquals("top_logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + topLogprobs = new ChangeTrackingList(); + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ChatTokenLogProbabilityInfo.DeserializeChatTokenLogProbabilityInfo(item, options)); + } + topLogprobs = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ChatTokenLogProbabilityResult(token, logprob, bytes, topLogprobs, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityResult)} does not support writing '{options.Format}' format."); + } + } + + ChatTokenLogProbabilityResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatTokenLogProbabilityResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatTokenLogProbabilityResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ChatTokenLogProbabilityResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatTokenLogProbabilityResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.cs new file mode 100644 index 000000000000..d7fe8b840266 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ChatTokenLogProbabilityResult.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// A representation of the log probability information for a single content token, including a list of most likely tokens if 'top_logprobs' were requested. + public partial class ChatTokenLogProbabilityResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + /// is null. + internal ChatTokenLogProbabilityResult(string token, float logProbability, IEnumerable utf8ByteValues, IEnumerable topLogProbabilityEntries) + { + Argument.AssertNotNull(token, nameof(token)); + + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues?.ToList(); + TopLogProbabilityEntries = topLogProbabilityEntries?.ToList(); + } + + /// Initializes a new instance of . + /// The message content token. + /// The log probability of the message content token. + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + /// Keeps track of any properties unknown to the library. + internal ChatTokenLogProbabilityResult(string token, float logProbability, IReadOnlyList utf8ByteValues, IReadOnlyList topLogProbabilityEntries, IDictionary serializedAdditionalRawData) + { + Token = token; + LogProbability = logProbability; + Utf8ByteValues = utf8ByteValues; + TopLogProbabilityEntries = topLogProbabilityEntries; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ChatTokenLogProbabilityResult() + { + } + + /// The message content token. + public string Token { get; } + /// The log probability of the message content token. + public float LogProbability { get; } + /// A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token. + public IReadOnlyList Utf8ByteValues { get; } + /// The list of most likely tokens and their log probability information, as requested via 'top_logprobs'. + public IReadOnlyList TopLogProbabilityEntries { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.Serialization.cs new file mode 100644 index 000000000000..92abe900ea13 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.Serialization.cs @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class Choice : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Choice)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("text"u8); + writer.WriteStringValue(Text); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); + if (Optional.IsDefined(ContentFilterResults)) + { + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); + } + if (LogProbabilityModel != null) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteObjectValue(LogProbabilityModel, options); + } + else + { + writer.WriteNull("logprobs"); + } + if (FinishReason != null) + { + writer.WritePropertyName("finish_reason"u8); + writer.WriteStringValue(FinishReason.Value.ToString()); + } + else + { + writer.WriteNull("finish_reason"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Choice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Choice)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChoice(document.RootElement, options); + } + + internal static Choice DeserializeChoice(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string text = default; + int index = default; + ContentFilterResultsForChoice contentFilterResults = default; + CompletionsLogProbabilityModel logprobs = default; + CompletionsFinishReason? finishReason = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("text"u8)) + { + text = property.Value.GetString(); + continue; + } + if (property.NameEquals("index"u8)) + { + index = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("content_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + contentFilterResults = ContentFilterResultsForChoice.DeserializeContentFilterResultsForChoice(property.Value, options); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + logprobs = null; + continue; + } + logprobs = CompletionsLogProbabilityModel.DeserializeCompletionsLogProbabilityModel(property.Value, options); + continue; + } + if (property.NameEquals("finish_reason"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + finishReason = null; + continue; + } + finishReason = new CompletionsFinishReason(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Choice( + text, + index, + contentFilterResults, + logprobs, + finishReason, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Choice)} does not support writing '{options.Format}' format."); + } + } + + Choice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChoice(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Choice)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Choice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChoice(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.cs new file mode 100644 index 000000000000..167dc6a38b70 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Choice.cs @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class Choice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The generated text for a given completions prompt. + /// The ordered index associated with this completions choice. + /// The log probabilities model for tokens associated with this completions choice. + /// Reason for finishing. + /// is null. + internal Choice(string text, int index, CompletionsLogProbabilityModel logProbabilityModel, CompletionsFinishReason? finishReason) + { + Argument.AssertNotNull(text, nameof(text)); + + Text = text; + Index = index; + LogProbabilityModel = logProbabilityModel; + FinishReason = finishReason; + } + + /// Initializes a new instance of . + /// The generated text for a given completions prompt. + /// The ordered index associated with this completions choice. + /// + /// 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. + /// + /// The log probabilities model for tokens associated with this completions choice. + /// Reason for finishing. + /// Keeps track of any properties unknown to the library. + internal Choice(string text, int index, ContentFilterResultsForChoice contentFilterResults, CompletionsLogProbabilityModel logProbabilityModel, CompletionsFinishReason? finishReason, IDictionary serializedAdditionalRawData) + { + Text = text; + Index = index; + ContentFilterResults = contentFilterResults; + LogProbabilityModel = logProbabilityModel; + FinishReason = finishReason; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Choice() + { + } + + /// The generated text for a given completions prompt. + public string Text { get; } + /// The ordered index associated with this completions choice. + public int Index { get; } + /// + /// 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. + /// + public ContentFilterResultsForChoice ContentFilterResults { get; } + /// The log probabilities model for tokens associated with this completions choice. + public CompletionsLogProbabilityModel LogProbabilityModel { get; } + /// Reason for finishing. + public CompletionsFinishReason? FinishReason { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.Serialization.cs new file mode 100644 index 000000000000..985da96cda03 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.Serialization.cs @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompleteUploadRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompleteUploadRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("part_ids"u8); + writer.WriteStartArray(); + foreach (var item in PartIds) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(Md5)) + { + writer.WritePropertyName("md5"u8); + writer.WriteStringValue(Md5); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CompleteUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompleteUploadRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompleteUploadRequest(document.RootElement, options); + } + + internal static CompleteUploadRequest DeserializeCompleteUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList partIds = default; + string md5 = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("part_ids"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + partIds = array; + continue; + } + if (property.NameEquals("md5"u8)) + { + md5 = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompleteUploadRequest(partIds, md5, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CompleteUploadRequest)} does not support writing '{options.Format}' format."); + } + } + + CompleteUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompleteUploadRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompleteUploadRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompleteUploadRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompleteUploadRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.cs new file mode 100644 index 000000000000..0022308524f9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompleteUploadRequest.cs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The request body of an upload completion request. + public partial class CompleteUploadRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ordered list of Part IDs. + /// is null. + public CompleteUploadRequest(IEnumerable partIds) + { + Argument.AssertNotNull(partIds, nameof(partIds)); + + PartIds = partIds.ToList(); + } + + /// Initializes a new instance of . + /// The ordered list of Part IDs. + /// The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. + /// Keeps track of any properties unknown to the library. + internal CompleteUploadRequest(IList partIds, string md5, IDictionary serializedAdditionalRawData) + { + PartIds = partIds; + Md5 = md5; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompleteUploadRequest() + { + } + + /// The ordered list of Part IDs. + public IList PartIds { get; } + /// The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect. + public string Md5 { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.Serialization.cs new file mode 100644 index 000000000000..986f81c4174a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.Serialization.cs @@ -0,0 +1,226 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class Completions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Completions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(Created, "U"); + if (Optional.IsCollectionDefined(PromptFilterResults)) + { + writer.WritePropertyName("prompt_filter_results"u8); + writer.WriteStartArray(); + foreach (var item in PromptFilterResults) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + writer.WritePropertyName("choices"u8); + writer.WriteStartArray(); + foreach (var item in Choices) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (Optional.IsDefined(Usage)) + { + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + } + if (Optional.IsDefined(SystemFingerprint)) + { + writer.WritePropertyName("system_fingerprint"u8); + writer.WriteStringValue(SystemFingerprint); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Completions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Completions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletions(document.RootElement, options); + } + + internal static Completions DeserializeCompletions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset created = default; + IReadOnlyList promptFilterResults = default; + IReadOnlyList choices = default; + CompletionsUsage usage = default; + string systemFingerprint = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created"u8)) + { + created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("prompt_filter_results"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ContentFilterResultsForPrompt.DeserializeContentFilterResultsForPrompt(item, options)); + } + promptFilterResults = array; + continue; + } + if (property.NameEquals("choices"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(Choice.DeserializeChoice(item, options)); + } + choices = array; + continue; + } + if (property.NameEquals("usage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + usage = CompletionsUsage.DeserializeCompletionsUsage(property.Value, options); + continue; + } + if (property.NameEquals("system_fingerprint"u8)) + { + systemFingerprint = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Completions( + id, + created, + promptFilterResults ?? new ChangeTrackingList(), + choices, + usage, + systemFingerprint, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Completions)} does not support writing '{options.Format}' format."); + } + } + + Completions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Completions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Completions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.cs new file mode 100644 index 000000000000..7d255eed2548 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Completions.cs @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class Completions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A unique identifier associated with this completions response. + /// + /// 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. + /// + /// + /// 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. + /// + /// or is null. + internal Completions(string id, DateTimeOffset created, IEnumerable choices) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(choices, nameof(choices)); + + Id = id; + Created = created; + PromptFilterResults = new ChangeTrackingList(); + Choices = choices.ToList(); + } + + /// Initializes a new instance of . + /// A unique identifier associated with this completions response. + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// 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. + /// + /// Usage information for tokens processed and generated as part of this completions operation. + /// + /// This fingerprint represents the backend configuration that the model runs with. + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + /// + /// Keeps track of any properties unknown to the library. + internal Completions(string id, DateTimeOffset created, IReadOnlyList promptFilterResults, IReadOnlyList choices, CompletionsUsage usage, string systemFingerprint, IDictionary serializedAdditionalRawData) + { + Id = id; + Created = created; + PromptFilterResults = promptFilterResults; + Choices = choices; + Usage = usage; + SystemFingerprint = systemFingerprint; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Completions() + { + } + + /// A unique identifier associated with this completions response. + public string Id { get; } + /// + /// 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. + /// + public DateTimeOffset Created { get; } + /// + /// 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. + /// + public IReadOnlyList PromptFilterResults { get; } + /// + /// 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. + /// + public IReadOnlyList Choices { get; } + /// Usage information for tokens processed and generated as part of this completions operation. + public CompletionsUsage Usage { get; } + /// + /// This fingerprint represents the backend configuration that the model runs with. + /// + /// Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. + /// + public string SystemFingerprint { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsFinishReason.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsFinishReason.cs new file mode 100644 index 000000000000..4270844fe202 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsFinishReason.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Representation of the manner in which a completions response concluded. + public readonly partial struct CompletionsFinishReason : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CompletionsFinishReason(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string StoppedValue = "stop"; + private const string TokenLimitReachedValue = "length"; + private const string ContentFilteredValue = "content_filter"; + private const string FunctionCallValue = "function_call"; + private const string ToolCallsValue = "tool_calls"; + + /// Completions ended normally and reached its end of token generation. + public static CompletionsFinishReason Stopped { get; } = new CompletionsFinishReason(StoppedValue); + /// Completions exhausted available token limits before generation could complete. + public static CompletionsFinishReason TokenLimitReached { get; } = new CompletionsFinishReason(TokenLimitReachedValue); + /// + /// Completions generated a response that was identified as potentially sensitive per content + /// moderation policies. + /// + public static CompletionsFinishReason ContentFiltered { get; } = new CompletionsFinishReason(ContentFilteredValue); + /// Completion ended normally, with the model requesting a function to be called. + public static CompletionsFinishReason FunctionCall { get; } = new CompletionsFinishReason(FunctionCallValue); + /// Completion ended with the model calling a provided tool for output. + public static CompletionsFinishReason ToolCalls { get; } = new CompletionsFinishReason(ToolCallsValue); + /// Determines if two values are the same. + public static bool operator ==(CompletionsFinishReason left, CompletionsFinishReason right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CompletionsFinishReason left, CompletionsFinishReason right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CompletionsFinishReason(string value) => new CompletionsFinishReason(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CompletionsFinishReason other && Equals(other); + /// + public bool Equals(CompletionsFinishReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.Serialization.cs new file mode 100644 index 000000000000..1542497f04e6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.Serialization.cs @@ -0,0 +1,253 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsLogProbabilityModel : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsLogProbabilityModel)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("tokens"u8); + writer.WriteStartArray(); + foreach (var item in Tokens) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("token_logprobs"u8); + writer.WriteStartArray(); + foreach (var item in TokenLogProbabilities) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteNumberValue(item.Value); + } + writer.WriteEndArray(); + writer.WritePropertyName("top_logprobs"u8); + writer.WriteStartArray(); + foreach (var item in TopLogProbabilities) + { + if (item == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteStartObject(); + foreach (var item0 in item) + { + writer.WritePropertyName(item0.Key); + if (item0.Value == null) + { + writer.WriteNullValue(); + continue; + } + writer.WriteNumberValue(item0.Value.Value); + } + writer.WriteEndObject(); + } + writer.WriteEndArray(); + writer.WritePropertyName("text_offset"u8); + writer.WriteStartArray(); + foreach (var item in TextOffsets) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CompletionsLogProbabilityModel IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsLogProbabilityModel)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsLogProbabilityModel(document.RootElement, options); + } + + internal static CompletionsLogProbabilityModel DeserializeCompletionsLogProbabilityModel(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList tokens = default; + IReadOnlyList tokenLogprobs = default; + IReadOnlyList> topLogprobs = default; + IReadOnlyList textOffset = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("tokens"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + tokens = array; + continue; + } + if (property.NameEquals("token_logprobs"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + array.Add(item.GetSingle()); + } + } + tokenLogprobs = array; + continue; + } + if (property.NameEquals("top_logprobs"u8)) + { + List> array = new List>(); + foreach (var item in property.Value.EnumerateArray()) + { + if (item.ValueKind == JsonValueKind.Null) + { + array.Add(null); + } + else + { + Dictionary dictionary = new Dictionary(); + foreach (var property0 in item.EnumerateObject()) + { + if (property0.Value.ValueKind == JsonValueKind.Null) + { + dictionary.Add(property0.Name, null); + } + else + { + dictionary.Add(property0.Name, property0.Value.GetSingle()); + } + } + array.Add(dictionary); + } + } + topLogprobs = array; + continue; + } + if (property.NameEquals("text_offset"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetInt32()); + } + textOffset = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsLogProbabilityModel(tokens, tokenLogprobs, topLogprobs, textOffset, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CompletionsLogProbabilityModel)} does not support writing '{options.Format}' format."); + } + } + + CompletionsLogProbabilityModel IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsLogProbabilityModel(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsLogProbabilityModel)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsLogProbabilityModel FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsLogProbabilityModel(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.cs new file mode 100644 index 000000000000..5b486eac6e8c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsLogProbabilityModel.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Representation of a log probabilities model for a completions generation. + public partial class CompletionsLogProbabilityModel + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The textual forms of tokens evaluated in this probability model. + /// A collection of log probability values for the tokens in this completions data. + /// A mapping of tokens to maximum log probability values in this completions data. + /// The text offsets associated with tokens in this completions data. + /// , , or is null. + internal CompletionsLogProbabilityModel(IEnumerable tokens, IEnumerable tokenLogProbabilities, IEnumerable> topLogProbabilities, IEnumerable textOffsets) + { + Argument.AssertNotNull(tokens, nameof(tokens)); + Argument.AssertNotNull(tokenLogProbabilities, nameof(tokenLogProbabilities)); + Argument.AssertNotNull(topLogProbabilities, nameof(topLogProbabilities)); + Argument.AssertNotNull(textOffsets, nameof(textOffsets)); + + Tokens = tokens.ToList(); + TokenLogProbabilities = tokenLogProbabilities.ToList(); + TopLogProbabilities = topLogProbabilities.ToList(); + TextOffsets = textOffsets.ToList(); + } + + /// Initializes a new instance of . + /// The textual forms of tokens evaluated in this probability model. + /// A collection of log probability values for the tokens in this completions data. + /// A mapping of tokens to maximum log probability values in this completions data. + /// The text offsets associated with tokens in this completions data. + /// Keeps track of any properties unknown to the library. + internal CompletionsLogProbabilityModel(IReadOnlyList tokens, IReadOnlyList tokenLogProbabilities, IReadOnlyList> topLogProbabilities, IReadOnlyList textOffsets, IDictionary serializedAdditionalRawData) + { + Tokens = tokens; + TokenLogProbabilities = tokenLogProbabilities; + TopLogProbabilities = topLogProbabilities; + TextOffsets = textOffsets; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompletionsLogProbabilityModel() + { + } + + /// The textual forms of tokens evaluated in this probability model. + public IReadOnlyList Tokens { get; } + /// A collection of log probability values for the tokens in this completions data. + public IReadOnlyList TokenLogProbabilities { get; } + /// A mapping of tokens to maximum log probability values in this completions data. + public IReadOnlyList> TopLogProbabilities { get; } + /// The text offsets associated with tokens in this completions data. + public IReadOnlyList TextOffsets { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.Serialization.cs new file mode 100644 index 000000000000..4169e9197f69 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.Serialization.cs @@ -0,0 +1,443 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("prompt"u8); + writer.WriteStartArray(); + foreach (var item in Prompts) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(MaxTokens)) + { + writer.WritePropertyName("max_tokens"u8); + writer.WriteNumberValue(MaxTokens.Value); + } + if (Optional.IsDefined(Temperature)) + { + writer.WritePropertyName("temperature"u8); + writer.WriteNumberValue(Temperature.Value); + } + if (Optional.IsDefined(NucleusSamplingFactor)) + { + writer.WritePropertyName("top_p"u8); + writer.WriteNumberValue(NucleusSamplingFactor.Value); + } + if (Optional.IsCollectionDefined(TokenSelectionBiases)) + { + writer.WritePropertyName("logit_bias"u8); + writer.WriteStartObject(); + foreach (var item in TokenSelectionBiases) + { + writer.WritePropertyName(item.Key); + writer.WriteNumberValue(item.Value); + } + writer.WriteEndObject(); + } + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (Optional.IsDefined(ChoicesPerPrompt)) + { + writer.WritePropertyName("n"u8); + writer.WriteNumberValue(ChoicesPerPrompt.Value); + } + if (Optional.IsDefined(LogProbabilityCount)) + { + writer.WritePropertyName("logprobs"u8); + writer.WriteNumberValue(LogProbabilityCount.Value); + } + if (Optional.IsDefined(Suffix)) + { + writer.WritePropertyName("suffix"u8); + writer.WriteStringValue(Suffix); + } + if (Optional.IsDefined(Echo)) + { + writer.WritePropertyName("echo"u8); + writer.WriteBooleanValue(Echo.Value); + } + if (Optional.IsCollectionDefined(StopSequences)) + { + writer.WritePropertyName("stop"u8); + writer.WriteStartArray(); + foreach (var item in StopSequences) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(PresencePenalty)) + { + writer.WritePropertyName("presence_penalty"u8); + writer.WriteNumberValue(PresencePenalty.Value); + } + if (Optional.IsDefined(FrequencyPenalty)) + { + writer.WritePropertyName("frequency_penalty"u8); + writer.WriteNumberValue(FrequencyPenalty.Value); + } + if (Optional.IsDefined(GenerationSampleCount)) + { + writer.WritePropertyName("best_of"u8); + writer.WriteNumberValue(GenerationSampleCount.Value); + } + if (Optional.IsDefined(InternalShouldStreamResponse)) + { + writer.WritePropertyName("stream"u8); + writer.WriteBooleanValue(InternalShouldStreamResponse.Value); + } + if (Optional.IsDefined(StreamOptions)) + { + if (StreamOptions != null) + { + writer.WritePropertyName("stream_options"u8); + writer.WriteObjectValue(StreamOptions, options); + } + else + { + writer.WriteNull("stream_options"); + } + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (Optional.IsDefined(Seed)) + { + writer.WritePropertyName("seed"u8); + writer.WriteNumberValue(Seed.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CompletionsOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsOptions(document.RootElement, options); + } + + internal static CompletionsOptions DeserializeCompletionsOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList prompt = default; + int? maxTokens = default; + float? temperature = default; + float? topP = default; + IDictionary logitBias = default; + string user = default; + int? n = default; + int? logprobs = default; + string suffix = default; + bool? echo = default; + IList stop = default; + float? presencePenalty = default; + float? frequencyPenalty = default; + int? bestOf = default; + bool? stream = default; + ChatCompletionStreamOptions streamOptions = default; + string model = default; + int? seed = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("prompt"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + prompt = array; + continue; + } + if (property.NameEquals("max_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("temperature"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + temperature = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("top_p"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topP = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("logit_bias"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + Dictionary dictionary = new Dictionary(); + foreach (var property0 in property.Value.EnumerateObject()) + { + dictionary.Add(property0.Name, property0.Value.GetInt32()); + } + logitBias = dictionary; + continue; + } + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (property.NameEquals("n"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + n = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("logprobs"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + logprobs = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("suffix"u8)) + { + suffix = property.Value.GetString(); + continue; + } + if (property.NameEquals("echo"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + echo = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stop"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + stop = array; + continue; + } + if (property.NameEquals("presence_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + presencePenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("frequency_penalty"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + frequencyPenalty = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("best_of"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + bestOf = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("stream"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + stream = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("stream_options"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + streamOptions = null; + continue; + } + streamOptions = ChatCompletionStreamOptions.DeserializeChatCompletionStreamOptions(property.Value, options); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("seed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + seed = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsOptions( + prompt, + maxTokens, + temperature, + topP, + logitBias ?? new ChangeTrackingDictionary(), + user, + n, + logprobs, + suffix, + echo, + stop ?? new ChangeTrackingList(), + presencePenalty, + frequencyPenalty, + bestOf, + stream, + streamOptions, + model, + seed, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CompletionsOptions)} does not support writing '{options.Format}' format."); + } + } + + CompletionsOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.cs new file mode 100644 index 000000000000..0e88c5d42c95 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsOptions.cs @@ -0,0 +1,266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class CompletionsOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The prompts to generate completions from. + /// is null. + public CompletionsOptions(IEnumerable prompts) + { + Argument.AssertNotNull(prompts, nameof(prompts)); + + Prompts = prompts.ToList(); + TokenSelectionBiases = new ChangeTrackingDictionary(); + StopSequences = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The prompts to generate completions from. + /// The maximum number of tokens to generate. + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + /// + /// 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. + /// + /// + /// A value that controls the emission of log probabilities for the provided number of most likely + /// tokens within a completions response. + /// + /// The suffix that comes after a completion of inserted text. + /// + /// A value specifying whether completions responses should include input prompts as prefixes to + /// their generated output. + /// + /// A collection of textual sequences that will end completions generation. + /// + /// 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. + /// + /// + /// 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. + /// + /// + /// 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. + /// + /// A value indicating whether chat completions should be streamed for this request. + /// Options for streaming response. Only set this when you set `stream: true`. + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + /// + /// If specified, our 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. + /// + /// Keeps track of any properties unknown to the library. + internal CompletionsOptions(IList prompts, int? maxTokens, float? temperature, float? nucleusSamplingFactor, IDictionary tokenSelectionBiases, string user, int? choicesPerPrompt, int? logProbabilityCount, string suffix, bool? echo, IList stopSequences, float? presencePenalty, float? frequencyPenalty, int? generationSampleCount, bool? internalShouldStreamResponse, ChatCompletionStreamOptions streamOptions, string deploymentName, int? seed, IDictionary serializedAdditionalRawData) + { + Prompts = prompts; + MaxTokens = maxTokens; + Temperature = temperature; + NucleusSamplingFactor = nucleusSamplingFactor; + TokenSelectionBiases = tokenSelectionBiases; + User = user; + ChoicesPerPrompt = choicesPerPrompt; + LogProbabilityCount = logProbabilityCount; + Suffix = suffix; + Echo = echo; + StopSequences = stopSequences; + PresencePenalty = presencePenalty; + FrequencyPenalty = frequencyPenalty; + GenerationSampleCount = generationSampleCount; + InternalShouldStreamResponse = internalShouldStreamResponse; + StreamOptions = streamOptions; + DeploymentName = deploymentName; + Seed = seed; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompletionsOptions() + { + } + + /// The prompts to generate completions from. + public IList Prompts { get; } + /// The maximum number of tokens to generate. + public int? MaxTokens { get; set; } + /// + /// 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. + /// + public float? Temperature { get; set; } + /// + /// 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. + /// + public float? NucleusSamplingFactor { get; set; } + /// + /// 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. + /// + public IDictionary TokenSelectionBiases { get; } + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + public string User { get; set; } + /// + /// 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. + /// + public int? ChoicesPerPrompt { get; set; } + /// + /// A value that controls the emission of log probabilities for the provided number of most likely + /// tokens within a completions response. + /// + public int? LogProbabilityCount { get; set; } + /// The suffix that comes after a completion of inserted text. + public string Suffix { get; set; } + /// + /// A value specifying whether completions responses should include input prompts as prefixes to + /// their generated output. + /// + public bool? Echo { get; set; } + /// A collection of textual sequences that will end completions generation. + public IList StopSequences { get; } + /// + /// 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. + /// + public float? PresencePenalty { get; set; } + /// + /// 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. + /// + public float? FrequencyPenalty { get; set; } + /// + /// 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. + /// + public int? GenerationSampleCount { get; set; } + /// A value indicating whether chat completions should be streamed for this request. + public bool? InternalShouldStreamResponse { get; set; } + /// Options for streaming response. Only set this when you set `stream: true`. + public ChatCompletionStreamOptions StreamOptions { get; set; } + /// + /// The model name to provide as part of this completions request. + /// Not applicable to Azure OpenAI, where deployment information should be included in the Azure + /// resource URI that's connected to. + /// + public string DeploymentName { get; set; } + /// + /// If specified, our 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. + /// + public int? Seed { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.Serialization.cs new file mode 100644 index 000000000000..875e80c1ae7b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.Serialization.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsUsage)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("completion_tokens"u8); + writer.WriteNumberValue(CompletionTokens); + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (Optional.IsDefined(PromptTokensDetails)) + { + writer.WritePropertyName("prompt_tokens_details"u8); + writer.WriteObjectValue(PromptTokensDetails, options); + } + if (Optional.IsDefined(CompletionTokensDetails)) + { + writer.WritePropertyName("completion_tokens_details"u8); + writer.WriteObjectValue(CompletionTokensDetails, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CompletionsUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsUsage(document.RootElement, options); + } + + internal static CompletionsUsage DeserializeCompletionsUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int completionTokens = default; + int promptTokens = default; + int totalTokens = default; + CompletionsUsagePromptTokensDetails promptTokensDetails = default; + CompletionsUsageCompletionTokensDetails completionTokensDetails = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("completion_tokens"u8)) + { + completionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("prompt_tokens_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + promptTokensDetails = CompletionsUsagePromptTokensDetails.DeserializeCompletionsUsagePromptTokensDetails(property.Value, options); + continue; + } + if (property.NameEquals("completion_tokens_details"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + completionTokensDetails = CompletionsUsageCompletionTokensDetails.DeserializeCompletionsUsageCompletionTokensDetails(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsUsage( + completionTokens, + promptTokens, + totalTokens, + promptTokensDetails, + completionTokensDetails, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CompletionsUsage)} does not support writing '{options.Format}' format."); + } + } + + CompletionsUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.cs new file mode 100644 index 000000000000..4416894b9eeb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsage.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// Representation of the token counts processed for a completions request. + /// Counts consider all tokens across prompts, choices, choice alternates, best_of generations, and + /// other consumers. + /// + public partial class CompletionsUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The number of tokens generated across all completions emissions. + /// The number of tokens in the provided prompts for the completions request. + /// The total number of tokens processed for the completions request and response. + internal CompletionsUsage(int completionTokens, int promptTokens, int totalTokens) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// The number of tokens generated across all completions emissions. + /// The number of tokens in the provided prompts for the completions request. + /// The total number of tokens processed for the completions request and response. + /// Details of the prompt tokens. + /// Breakdown of tokens used in a completion. + /// Keeps track of any properties unknown to the library. + internal CompletionsUsage(int completionTokens, int promptTokens, int totalTokens, CompletionsUsagePromptTokensDetails promptTokensDetails, CompletionsUsageCompletionTokensDetails completionTokensDetails, IDictionary serializedAdditionalRawData) + { + CompletionTokens = completionTokens; + PromptTokens = promptTokens; + TotalTokens = totalTokens; + PromptTokensDetails = promptTokensDetails; + CompletionTokensDetails = completionTokensDetails; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CompletionsUsage() + { + } + + /// The number of tokens generated across all completions emissions. + public int CompletionTokens { get; } + /// The number of tokens in the provided prompts for the completions request. + public int PromptTokens { get; } + /// The total number of tokens processed for the completions request and response. + public int TotalTokens { get; } + /// Details of the prompt tokens. + public CompletionsUsagePromptTokensDetails PromptTokensDetails { get; } + /// Breakdown of tokens used in a completion. + public CompletionsUsageCompletionTokensDetails CompletionTokensDetails { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.Serialization.cs new file mode 100644 index 000000000000..2dbf8392e3cb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.Serialization.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsUsageCompletionTokensDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsUsageCompletionTokensDetails)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(AcceptedPredictionTokens)) + { + writer.WritePropertyName("accepted_prediction_tokens"u8); + writer.WriteNumberValue(AcceptedPredictionTokens.Value); + } + if (Optional.IsDefined(AudioTokens)) + { + writer.WritePropertyName("audio_tokens"u8); + writer.WriteNumberValue(AudioTokens.Value); + } + if (Optional.IsDefined(ReasoningTokens)) + { + writer.WritePropertyName("reasoning_tokens"u8); + writer.WriteNumberValue(ReasoningTokens.Value); + } + if (Optional.IsDefined(RejectedPredictionTokens)) + { + writer.WritePropertyName("rejected_prediction_tokens"u8); + writer.WriteNumberValue(RejectedPredictionTokens.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CompletionsUsageCompletionTokensDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsUsageCompletionTokensDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsUsageCompletionTokensDetails(document.RootElement, options); + } + + internal static CompletionsUsageCompletionTokensDetails DeserializeCompletionsUsageCompletionTokensDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? acceptedPredictionTokens = default; + int? audioTokens = default; + int? reasoningTokens = default; + int? rejectedPredictionTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("accepted_prediction_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + acceptedPredictionTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("audio_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + audioTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("reasoning_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + reasoningTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("rejected_prediction_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + rejectedPredictionTokens = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsUsageCompletionTokensDetails(acceptedPredictionTokens, audioTokens, reasoningTokens, rejectedPredictionTokens, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CompletionsUsageCompletionTokensDetails)} does not support writing '{options.Format}' format."); + } + } + + CompletionsUsageCompletionTokensDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsUsageCompletionTokensDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsUsageCompletionTokensDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsUsageCompletionTokensDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsUsageCompletionTokensDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.cs new file mode 100644 index 000000000000..159dca2342db --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsageCompletionTokensDetails.cs @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The CompletionsUsageCompletionTokensDetails. + public partial class CompletionsUsageCompletionTokensDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal CompletionsUsageCompletionTokensDetails() + { + } + + /// Initializes a new instance of . + /// + /// When using Predicted Outputs, the number of tokens in the + /// prediction that appeared in the completion. + /// + /// Audio input tokens generated by the model. + /// Tokens generated by the model for reasoning. + /// + /// When using Predicted Outputs, the number of tokens in the + /// prediction that did not appear in the completion. However, like + /// reasoning tokens, these tokens are still counted in the total + /// completion tokens for purposes of billing, output, and context + /// window limits. + /// + /// Keeps track of any properties unknown to the library. + internal CompletionsUsageCompletionTokensDetails(int? acceptedPredictionTokens, int? audioTokens, int? reasoningTokens, int? rejectedPredictionTokens, IDictionary serializedAdditionalRawData) + { + AcceptedPredictionTokens = acceptedPredictionTokens; + AudioTokens = audioTokens; + ReasoningTokens = reasoningTokens; + RejectedPredictionTokens = rejectedPredictionTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// When using Predicted Outputs, the number of tokens in the + /// prediction that appeared in the completion. + /// + public int? AcceptedPredictionTokens { get; } + /// Audio input tokens generated by the model. + public int? AudioTokens { get; } + /// Tokens generated by the model for reasoning. + public int? ReasoningTokens { get; } + /// + /// When using Predicted Outputs, the number of tokens in the + /// prediction that did not appear in the completion. However, like + /// reasoning tokens, these tokens are still counted in the total + /// completion tokens for purposes of billing, output, and context + /// window limits. + /// + public int? RejectedPredictionTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.Serialization.cs new file mode 100644 index 000000000000..d74ca5b1f6d3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.Serialization.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CompletionsUsagePromptTokensDetails : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsUsagePromptTokensDetails)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(AudioTokens)) + { + writer.WritePropertyName("audio_tokens"u8); + writer.WriteNumberValue(AudioTokens.Value); + } + if (Optional.IsDefined(CachedTokens)) + { + writer.WritePropertyName("cached_tokens"u8); + writer.WriteNumberValue(CachedTokens.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CompletionsUsagePromptTokensDetails IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CompletionsUsagePromptTokensDetails)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCompletionsUsagePromptTokensDetails(document.RootElement, options); + } + + internal static CompletionsUsagePromptTokensDetails DeserializeCompletionsUsagePromptTokensDetails(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? audioTokens = default; + int? cachedTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("audio_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + audioTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("cached_tokens"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + cachedTokens = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CompletionsUsagePromptTokensDetails(audioTokens, cachedTokens, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CompletionsUsagePromptTokensDetails)} does not support writing '{options.Format}' format."); + } + } + + CompletionsUsagePromptTokensDetails IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsUsagePromptTokensDetails(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CompletionsUsagePromptTokensDetails)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CompletionsUsagePromptTokensDetails FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCompletionsUsagePromptTokensDetails(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.cs new file mode 100644 index 000000000000..4137069922cb --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CompletionsUsagePromptTokensDetails.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The CompletionsUsagePromptTokensDetails. + public partial class CompletionsUsagePromptTokensDetails + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal CompletionsUsagePromptTokensDetails() + { + } + + /// Initializes a new instance of . + /// Audio input tokens present in the prompt. + /// Cached tokens present in the prompt. + /// Keeps track of any properties unknown to the library. + internal CompletionsUsagePromptTokensDetails(int? audioTokens, int? cachedTokens, IDictionary serializedAdditionalRawData) + { + AudioTokens = audioTokens; + CachedTokens = cachedTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Audio input tokens present in the prompt. + public int? AudioTokens { get; } + /// Cached tokens present in the prompt. + public int? CachedTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.Serialization.cs new file mode 100644 index 000000000000..6ef1ee2e82dc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterBlocklistIdResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterBlocklistIdResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterBlocklistIdResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterBlocklistIdResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterBlocklistIdResult(document.RootElement, options); + } + + internal static ContentFilterBlocklistIdResult DeserializeContentFilterBlocklistIdResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + string id = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterBlocklistIdResult(filtered, id, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterBlocklistIdResult)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterBlocklistIdResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterBlocklistIdResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterBlocklistIdResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterBlocklistIdResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterBlocklistIdResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.cs new file mode 100644 index 000000000000..012d845ccce3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterBlocklistIdResult.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the outcome of an evaluation against a custom blocklist as performed by content filtering. + public partial class ContentFilterBlocklistIdResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The ID of the custom blocklist evaluated. + /// is null. + internal ContentFilterBlocklistIdResult(bool filtered, string id) + { + Argument.AssertNotNull(id, nameof(id)); + + Filtered = filtered; + Id = id; + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The ID of the custom blocklist evaluated. + /// Keeps track of any properties unknown to the library. + internal ContentFilterBlocklistIdResult(bool filtered, string id, IDictionary serializedAdditionalRawData) + { + Filtered = filtered; + Id = id; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterBlocklistIdResult() + { + } + + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } + /// The ID of the custom blocklist evaluated. + public string Id { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.Serialization.cs new file mode 100644 index 000000000000..22d5288fc3ed --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.Serialization.cs @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterCitedDetectionResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterCitedDetectionResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("detected"u8); + writer.WriteBooleanValue(Detected); + if (Optional.IsDefined(Url)) + { + writer.WritePropertyName("URL"u8); + writer.WriteStringValue(Url.AbsoluteUri); + } + if (Optional.IsDefined(License)) + { + writer.WritePropertyName("license"u8); + writer.WriteStringValue(License); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterCitedDetectionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterCitedDetectionResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterCitedDetectionResult(document.RootElement, options); + } + + internal static ContentFilterCitedDetectionResult DeserializeContentFilterCitedDetectionResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + bool detected = default; + Uri url = default; + string license = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("detected"u8)) + { + detected = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("URL"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + url = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("license"u8)) + { + license = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterCitedDetectionResult(filtered, detected, url, license, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterCitedDetectionResult)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterCitedDetectionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterCitedDetectionResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterCitedDetectionResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterCitedDetectionResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterCitedDetectionResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.cs new file mode 100644 index 000000000000..5e73e0beb4b2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCitedDetectionResult.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the outcome of a detection operation against protected resources as performed by content filtering. + public partial class ContentFilterCitedDetectionResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + internal ContentFilterCitedDetectionResult(bool filtered, bool detected) + { + Filtered = filtered; + Detected = detected; + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// The internet location associated with the detection. + /// The license description associated with the detection. + /// Keeps track of any properties unknown to the library. + internal ContentFilterCitedDetectionResult(bool filtered, bool detected, Uri url, string license, IDictionary serializedAdditionalRawData) + { + Filtered = filtered; + Detected = detected; + Url = url; + License = license; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterCitedDetectionResult() + { + } + + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + public bool Detected { get; } + /// The internet location associated with the detection. + public Uri Url { get; } + /// The license description associated with the detection. + public string License { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.Serialization.cs new file mode 100644 index 000000000000..ca32ab236e8d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterCompletionTextSpan : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpan)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("completion_start_offset"u8); + writer.WriteNumberValue(CompletionStartOffset); + writer.WritePropertyName("completion_end_offset"u8); + writer.WriteNumberValue(CompletionEndOffset); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterCompletionTextSpan IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpan)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterCompletionTextSpan(document.RootElement, options); + } + + internal static ContentFilterCompletionTextSpan DeserializeContentFilterCompletionTextSpan(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int completionStartOffset = default; + int completionEndOffset = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("completion_start_offset"u8)) + { + completionStartOffset = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("completion_end_offset"u8)) + { + completionEndOffset = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterCompletionTextSpan(completionStartOffset, completionEndOffset, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpan)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterCompletionTextSpan IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterCompletionTextSpan(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpan)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterCompletionTextSpan FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterCompletionTextSpan(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.cs new file mode 100644 index 000000000000..ff2b77e48291 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpan.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Describes a span within generated completion text. Offset 0 is the first UTF32 code point of the completion text. + public partial class ContentFilterCompletionTextSpan + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Offset of the UTF32 code point which begins the span. + /// + /// Offset of the first UTF32 code point which is excluded from the span. + /// This field is always equal to completion_start_offset for empty spans. + /// This field is always larger than completion_start_offset for non-empty spans. + /// + internal ContentFilterCompletionTextSpan(int completionStartOffset, int completionEndOffset) + { + CompletionStartOffset = completionStartOffset; + CompletionEndOffset = completionEndOffset; + } + + /// Initializes a new instance of . + /// Offset of the UTF32 code point which begins the span. + /// + /// Offset of the first UTF32 code point which is excluded from the span. + /// This field is always equal to completion_start_offset for empty spans. + /// This field is always larger than completion_start_offset for non-empty spans. + /// + /// Keeps track of any properties unknown to the library. + internal ContentFilterCompletionTextSpan(int completionStartOffset, int completionEndOffset, IDictionary serializedAdditionalRawData) + { + CompletionStartOffset = completionStartOffset; + CompletionEndOffset = completionEndOffset; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterCompletionTextSpan() + { + } + + /// Offset of the UTF32 code point which begins the span. + public int CompletionStartOffset { get; } + /// + /// Offset of the first UTF32 code point which is excluded from the span. + /// This field is always equal to completion_start_offset for empty spans. + /// This field is always larger than completion_start_offset for non-empty spans. + /// + public int CompletionEndOffset { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.Serialization.cs similarity index 60% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.Serialization.cs index 4fb71cbac633..ace5b6fc524c 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionResult.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI { - public partial class CreateLivenessWithVerifySessionResult : IUtf8JsonSerializable, IJsonModel + public partial class ContentFilterCompletionTextSpanResult : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,21 +28,23 @@ void IJsonModel.Write(Utf8JsonWriter writ /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpanResult)} does not support writing '{format}' format."); } - writer.WritePropertyName("sessionId"u8); - writer.WriteStringValue(SessionId); - writer.WritePropertyName("authToken"u8); - writer.WriteStringValue(AuthToken); - if (Optional.IsDefined(VerifyImage)) + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("detected"u8); + writer.WriteBooleanValue(Detected); + writer.WritePropertyName("details"u8); + writer.WriteStartArray(); + foreach (var item in Details) { - writer.WritePropertyName("verifyImage"u8); - writer.WriteObjectValue(VerifyImage, options); + writer.WriteObjectValue(item, options); } + writer.WriteEndArray(); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -60,19 +62,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - CreateLivenessWithVerifySessionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ContentFilterCompletionTextSpanResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpanResult)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateLivenessWithVerifySessionResult(document.RootElement, options); + return DeserializeContentFilterCompletionTextSpanResult(document.RootElement, options); } - internal static CreateLivenessWithVerifySessionResult DeserializeCreateLivenessWithVerifySessionResult(JsonElement element, ModelReaderWriterOptions options = null) + internal static ContentFilterCompletionTextSpanResult DeserializeContentFilterCompletionTextSpanResult(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -80,30 +82,31 @@ internal static CreateLivenessWithVerifySessionResult DeserializeCreateLivenessW { return null; } - string sessionId = default; - string authToken = default; - LivenessWithVerifyImage verifyImage = default; + bool filtered = default; + bool detected = default; + IReadOnlyList details = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("sessionId"u8)) + if (property.NameEquals("filtered"u8)) { - sessionId = property.Value.GetString(); + filtered = property.Value.GetBoolean(); continue; } - if (property.NameEquals("authToken"u8)) + if (property.NameEquals("detected"u8)) { - authToken = property.Value.GetString(); + detected = property.Value.GetBoolean(); continue; } - if (property.NameEquals("verifyImage"u8)) + if (property.NameEquals("details"u8)) { - if (property.Value.ValueKind == JsonValueKind.Null) + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) { - continue; + array.Add(ContentFilterCompletionTextSpan.DeserializeContentFilterCompletionTextSpan(item, options)); } - verifyImage = LivenessWithVerifyImage.DeserializeLivenessWithVerifyImage(property.Value, options); + details = array; continue; } if (options.Format != "W") @@ -112,46 +115,46 @@ internal static CreateLivenessWithVerifySessionResult DeserializeCreateLivenessW } } serializedAdditionalRawData = rawDataDictionary; - return new CreateLivenessWithVerifySessionResult(sessionId, authToken, verifyImage, serializedAdditionalRawData); + return new ContentFilterCompletionTextSpanResult(filtered, detected, details, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpanResult)} does not support writing '{options.Format}' format."); } } - CreateLivenessWithVerifySessionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ContentFilterCompletionTextSpanResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionResult(document.RootElement, options); + return DeserializeContentFilterCompletionTextSpanResult(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionResult)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ContentFilterCompletionTextSpanResult)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateLivenessWithVerifySessionResult FromResponse(Response response) + internal static ContentFilterCompletionTextSpanResult FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionResult(document.RootElement); + return DeserializeContentFilterCompletionTextSpanResult(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.cs new file mode 100644 index 000000000000..6232e7fc70b0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterCompletionTextSpanResult.cs @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Describes a span within generated completion text. + public partial class ContentFilterCompletionTextSpanResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// The collection of completion text spans. + /// is null. + internal ContentFilterCompletionTextSpanResult(bool filtered, bool detected, IEnumerable details) + { + Argument.AssertNotNull(details, nameof(details)); + + Filtered = filtered; + Detected = detected; + Details = details.ToList(); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// The collection of completion text spans. + /// Keeps track of any properties unknown to the library. + internal ContentFilterCompletionTextSpanResult(bool filtered, bool detected, IReadOnlyList details, IDictionary serializedAdditionalRawData) + { + Filtered = filtered; + Detected = detected; + Details = details; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterCompletionTextSpanResult() + { + } + + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + public bool Detected { get; } + /// The collection of completion text spans. + public IReadOnlyList Details { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.Serialization.cs new file mode 100644 index 000000000000..4cbed1fad5b2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterDetailedResults : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("details"u8); + writer.WriteStartArray(); + foreach (var item in Details) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterDetailedResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterDetailedResults(document.RootElement, options); + } + + internal static ContentFilterDetailedResults DeserializeContentFilterDetailedResults(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + IReadOnlyList details = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("details"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ContentFilterBlocklistIdResult.DeserializeContentFilterBlocklistIdResult(item, options)); + } + details = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterDetailedResults(filtered, details, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterDetailedResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterDetailedResults(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterDetailedResults)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterDetailedResults FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterDetailedResults(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.cs new file mode 100644 index 000000000000..05de806d7b90 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetailedResults.cs @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Represents a structured collection of result details for content filtering. + public partial class ContentFilterDetailedResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The collection of detailed blocklist result information. + /// is null. + internal ContentFilterDetailedResults(bool filtered, IEnumerable details) + { + Argument.AssertNotNull(details, nameof(details)); + + Filtered = filtered; + Details = details.ToList(); + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// The collection of detailed blocklist result information. + /// Keeps track of any properties unknown to the library. + internal ContentFilterDetailedResults(bool filtered, IReadOnlyList details, IDictionary serializedAdditionalRawData) + { + Filtered = filtered; + Details = details; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterDetailedResults() + { + } + + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } + /// The collection of detailed blocklist result information. + public IReadOnlyList Details { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs new file mode 100644 index 000000000000..e1bf6714ede2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterDetectionResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("detected"u8); + writer.WriteBooleanValue(Detected); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterDetectionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterDetectionResult(document.RootElement, options); + } + + internal static ContentFilterDetectionResult DeserializeContentFilterDetectionResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + bool detected = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("detected"u8)) + { + detected = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterDetectionResult(filtered, detected, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterDetectionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterDetectionResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterDetectionResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterDetectionResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs new file mode 100644 index 000000000000..eed9a9faac26 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterDetectionResult.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the outcome of a detection operation performed by content filtering. + public partial class ContentFilterDetectionResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + internal ContentFilterDetectionResult(bool filtered, bool detected) + { + Filtered = filtered; + Detected = detected; + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + /// Keeps track of any properties unknown to the library. + internal ContentFilterDetectionResult(bool filtered, bool detected, IDictionary serializedAdditionalRawData) + { + Filtered = filtered; + Detected = detected; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterDetectionResult() + { + } + + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } + /// A value indicating whether detection occurred, irrespective of severity or whether the content was filtered. + public bool Detected { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.Serialization.cs new file mode 100644 index 000000000000..93b5c58cd1f5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("filtered"u8); + writer.WriteBooleanValue(Filtered); + writer.WritePropertyName("severity"u8); + writer.WriteStringValue(Severity.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterResult(document.RootElement, options); + } + + internal static ContentFilterResult DeserializeContentFilterResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool filtered = default; + ContentFilterSeverity severity = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filtered"u8)) + { + filtered = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("severity"u8)) + { + severity = new ContentFilterSeverity(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterResult(filtered, severity, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterResult)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.cs new file mode 100644 index 000000000000..ea7952376a34 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResult.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Information about filtered content severity level and if it has been filtered or not. + public partial class ContentFilterResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// Ratings for the intensity and risk level of filtered content. + internal ContentFilterResult(bool filtered, ContentFilterSeverity severity) + { + Filtered = filtered; + Severity = severity; + } + + /// Initializes a new instance of . + /// A value indicating whether or not the content has been filtered. + /// Ratings for the intensity and risk level of filtered content. + /// Keeps track of any properties unknown to the library. + internal ContentFilterResult(bool filtered, ContentFilterSeverity severity, IDictionary serializedAdditionalRawData) + { + Filtered = filtered; + Severity = severity; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterResult() + { + } + + /// A value indicating whether or not the content has been filtered. + public bool Filtered { get; } + /// Ratings for the intensity and risk level of filtered content. + public ContentFilterSeverity Severity { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.Serialization.cs new file mode 100644 index 000000000000..18dd36fbcb89 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.Serialization.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterResultDetailsForPrompt : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Sexual)) + { + writer.WritePropertyName("sexual"u8); + writer.WriteObjectValue(Sexual, options); + } + if (Optional.IsDefined(Violence)) + { + writer.WritePropertyName("violence"u8); + writer.WriteObjectValue(Violence, options); + } + if (Optional.IsDefined(Hate)) + { + writer.WritePropertyName("hate"u8); + writer.WriteObjectValue(Hate, options); + } + if (Optional.IsDefined(SelfHarm)) + { + writer.WritePropertyName("self_harm"u8); + writer.WriteObjectValue(SelfHarm, options); + } + if (Optional.IsDefined(Profanity)) + { + writer.WritePropertyName("profanity"u8); + writer.WriteObjectValue(Profanity, options); + } + if (Optional.IsDefined(CustomBlocklists)) + { + writer.WritePropertyName("custom_blocklists"u8); + writer.WriteObjectValue(CustomBlocklists, options); + } + if (Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + JsonSerializer.Serialize(writer, Error); + } + if (Optional.IsDefined(Jailbreak)) + { + writer.WritePropertyName("jailbreak"u8); + writer.WriteObjectValue(Jailbreak, options); + } + if (Optional.IsDefined(IndirectAttack)) + { + writer.WritePropertyName("indirect_attack"u8); + writer.WriteObjectValue(IndirectAttack, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterResultDetailsForPrompt IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterResultDetailsForPrompt(document.RootElement, options); + } + + internal static ContentFilterResultDetailsForPrompt DeserializeContentFilterResultDetailsForPrompt(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; + ContentFilterDetectionResult profanity = default; + ContentFilterDetailedResults customBlocklists = default; + ResponseError error = default; + ContentFilterDetectionResult jailbreak = default; + ContentFilterDetectionResult indirectAttack = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sexual"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("violence"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("hate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("self_harm"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("profanity"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + continue; + } + if (property.NameEquals("custom_blocklists"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + customBlocklists = ContentFilterDetailedResults.DeserializeContentFilterDetailedResults(property.Value, options); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = JsonSerializer.Deserialize(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("jailbreak"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + jailbreak = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + continue; + } + if (property.NameEquals("indirect_attack"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + indirectAttack = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterResultDetailsForPrompt( + sexual, + violence, + hate, + selfHarm, + profanity, + customBlocklists, + error, + jailbreak, + indirectAttack, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterResultDetailsForPrompt IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResultDetailsForPrompt(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterResultDetailsForPrompt)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterResultDetailsForPrompt FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResultDetailsForPrompt(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.cs new file mode 100644 index 000000000000..acec97c64cc9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultDetailsForPrompt.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Information about content filtering evaluated against input data to Azure OpenAI. + public partial class ContentFilterResultDetailsForPrompt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ContentFilterResultDetailsForPrompt() + { + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Whether a jailbreak attempt was detected in the prompt. + /// Whether an indirect attack was detected in the prompt. + /// Keeps track of any properties unknown to the library. + internal ContentFilterResultDetailsForPrompt(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterDetailedResults customBlocklists, ResponseError error, ContentFilterDetectionResult jailbreak, ContentFilterDetectionResult indirectAttack, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + Profanity = profanity; + CustomBlocklists = customBlocklists; + Error = error; + Jailbreak = jailbreak; + IndirectAttack = indirectAttack; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// 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. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// 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. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + /// Describes whether profanity was detected. + public ContentFilterDetectionResult Profanity { get; } + /// Describes detection results against configured custom blocklists. + public ContentFilterDetailedResults CustomBlocklists { get; } + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + public ResponseError Error { get; } + /// Whether a jailbreak attempt was detected in the prompt. + public ContentFilterDetectionResult Jailbreak { get; } + /// Whether an indirect attack was detected in the prompt. + public ContentFilterDetectionResult IndirectAttack { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.Serialization.cs new file mode 100644 index 000000000000..ee92713d04c8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.Serialization.cs @@ -0,0 +1,295 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterResultsForChoice : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Sexual)) + { + writer.WritePropertyName("sexual"u8); + writer.WriteObjectValue(Sexual, options); + } + if (Optional.IsDefined(Violence)) + { + writer.WritePropertyName("violence"u8); + writer.WriteObjectValue(Violence, options); + } + if (Optional.IsDefined(Hate)) + { + writer.WritePropertyName("hate"u8); + writer.WriteObjectValue(Hate, options); + } + if (Optional.IsDefined(SelfHarm)) + { + writer.WritePropertyName("self_harm"u8); + writer.WriteObjectValue(SelfHarm, options); + } + if (Optional.IsDefined(Profanity)) + { + writer.WritePropertyName("profanity"u8); + writer.WriteObjectValue(Profanity, options); + } + if (Optional.IsDefined(CustomBlocklists)) + { + writer.WritePropertyName("custom_blocklists"u8); + writer.WriteObjectValue(CustomBlocklists, options); + } + if (Optional.IsDefined(Error)) + { + writer.WritePropertyName("error"u8); + JsonSerializer.Serialize(writer, Error); + } + if (Optional.IsDefined(ProtectedMaterialText)) + { + writer.WritePropertyName("protected_material_text"u8); + writer.WriteObjectValue(ProtectedMaterialText, options); + } + if (Optional.IsDefined(ProtectedMaterialCode)) + { + writer.WritePropertyName("protected_material_code"u8); + writer.WriteObjectValue(ProtectedMaterialCode, options); + } + if (Optional.IsDefined(UngroundedMaterial)) + { + writer.WritePropertyName("ungrounded_material"u8); + writer.WriteObjectValue(UngroundedMaterial, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterResultsForChoice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterResultsForChoice(document.RootElement, options); + } + + internal static ContentFilterResultsForChoice DeserializeContentFilterResultsForChoice(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; + ContentFilterDetectionResult profanity = default; + ContentFilterDetailedResults customBlocklists = default; + ResponseError error = default; + ContentFilterDetectionResult protectedMaterialText = default; + ContentFilterCitedDetectionResult protectedMaterialCode = default; + ContentFilterCompletionTextSpanResult ungroundedMaterial = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sexual"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("violence"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("hate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("self_harm"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("profanity"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + continue; + } + if (property.NameEquals("custom_blocklists"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + customBlocklists = ContentFilterDetailedResults.DeserializeContentFilterDetailedResults(property.Value, options); + continue; + } + if (property.NameEquals("error"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + error = JsonSerializer.Deserialize(property.Value.GetRawText()); + continue; + } + if (property.NameEquals("protected_material_text"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + protectedMaterialText = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + continue; + } + if (property.NameEquals("protected_material_code"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + protectedMaterialCode = ContentFilterCitedDetectionResult.DeserializeContentFilterCitedDetectionResult(property.Value, options); + continue; + } + if (property.NameEquals("ungrounded_material"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + ungroundedMaterial = ContentFilterCompletionTextSpanResult.DeserializeContentFilterCompletionTextSpanResult(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterResultsForChoice( + sexual, + violence, + hate, + selfHarm, + profanity, + customBlocklists, + error, + protectedMaterialText, + protectedMaterialCode, + ungroundedMaterial, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterResultsForChoice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResultsForChoice(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterResultsForChoice)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterResultsForChoice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResultsForChoice(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.cs new file mode 100644 index 000000000000..5b7638e9d998 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForChoice.cs @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Information about content filtering evaluated against generated model output. + public partial class ContentFilterResultsForChoice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ContentFilterResultsForChoice() + { + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Describes detection results against configured custom blocklists. + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + /// Information about detection of protected text material. + /// Information about detection of protected code material. + /// Information about detection of ungrounded material. + /// Keeps track of any properties unknown to the library. + internal ContentFilterResultsForChoice(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterDetailedResults customBlocklists, ResponseError error, ContentFilterDetectionResult protectedMaterialText, ContentFilterCitedDetectionResult protectedMaterialCode, ContentFilterCompletionTextSpanResult ungroundedMaterial, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + Profanity = profanity; + CustomBlocklists = customBlocklists; + Error = error; + ProtectedMaterialText = protectedMaterialText; + ProtectedMaterialCode = protectedMaterialCode; + UngroundedMaterial = ungroundedMaterial; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// 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. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// 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. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + /// Describes whether profanity was detected. + public ContentFilterDetectionResult Profanity { get; } + /// Describes detection results against configured custom blocklists. + public ContentFilterDetailedResults CustomBlocklists { get; } + /// + /// Describes an error returned if the content filtering system is + /// down or otherwise unable to complete the operation in time. + /// + public ResponseError Error { get; } + /// Information about detection of protected text material. + public ContentFilterDetectionResult ProtectedMaterialText { get; } + /// Information about detection of protected code material. + public ContentFilterCitedDetectionResult ProtectedMaterialCode { get; } + /// Information about detection of ungrounded material. + public ContentFilterCompletionTextSpanResult UngroundedMaterial { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.Serialization.cs new file mode 100644 index 000000000000..def95abfce43 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ContentFilterResultsForPrompt : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResultsForPrompt)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("prompt_index"u8); + writer.WriteNumberValue(PromptIndex); + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ContentFilterResultsForPrompt IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ContentFilterResultsForPrompt)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeContentFilterResultsForPrompt(document.RootElement, options); + } + + internal static ContentFilterResultsForPrompt DeserializeContentFilterResultsForPrompt(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int promptIndex = default; + ContentFilterResultDetailsForPrompt contentFilterResults = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("prompt_index"u8)) + { + promptIndex = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("content_filter_results"u8)) + { + contentFilterResults = ContentFilterResultDetailsForPrompt.DeserializeContentFilterResultDetailsForPrompt(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ContentFilterResultsForPrompt(promptIndex, contentFilterResults, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ContentFilterResultsForPrompt)} does not support writing '{options.Format}' format."); + } + } + + ContentFilterResultsForPrompt IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResultsForPrompt(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ContentFilterResultsForPrompt)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ContentFilterResultsForPrompt FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeContentFilterResultsForPrompt(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.cs new file mode 100644 index 000000000000..4e411955a776 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterResultsForPrompt.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Content filtering results for a single prompt in the request. + public partial class ContentFilterResultsForPrompt + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The index of this prompt in the set of prompt results. + /// Content filtering results for this prompt. + /// is null. + internal ContentFilterResultsForPrompt(int promptIndex, ContentFilterResultDetailsForPrompt contentFilterResults) + { + Argument.AssertNotNull(contentFilterResults, nameof(contentFilterResults)); + + PromptIndex = promptIndex; + ContentFilterResults = contentFilterResults; + } + + /// Initializes a new instance of . + /// The index of this prompt in the set of prompt results. + /// Content filtering results for this prompt. + /// Keeps track of any properties unknown to the library. + internal ContentFilterResultsForPrompt(int promptIndex, ContentFilterResultDetailsForPrompt contentFilterResults, IDictionary serializedAdditionalRawData) + { + PromptIndex = promptIndex; + ContentFilterResults = contentFilterResults; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ContentFilterResultsForPrompt() + { + } + + /// The index of this prompt in the set of prompt results. + public int PromptIndex { get; } + /// Content filtering results for this prompt. + public ContentFilterResultDetailsForPrompt ContentFilterResults { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverity.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverity.cs similarity index 55% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverity.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverity.cs index 634101baecf2..4c49dd0aec22 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverity.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ContentFilterSeverity.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,63 +10,65 @@ namespace Azure.AI.OpenAI { - /// + /// Ratings for the intensity and risk level of harmful content. public readonly partial struct ContentFilterSeverity : IEquatable { private readonly string _value; - private const string SafeValue = "safe"; - private const string LowValue = "low"; - private const string MediumValue = "medium"; - private const string HighValue = "high"; /// Initializes a new instance of . - /// The value. /// is null. public ContentFilterSeverity(string value) { - Argument.AssertNotNull(value, nameof(value)); - - _value = value; + _value = value ?? throw new ArgumentNullException(nameof(value)); } - /// Gets the Safe. - public static ContentFilterSeverity Safe { get; } = new ContentFilterSeverity(SafeValue); + private const string SafeValue = "safe"; + private const string LowValue = "low"; + private const string MediumValue = "medium"; + private const string HighValue = "high"; - /// Gets the Low. + /// + /// Content may be related to violence, self-harm, sexual, or hate categories but the terms + /// are used in general, journalistic, scientific, medical, and similar professional contexts, + /// which are appropriate for most audiences. + /// + public static ContentFilterSeverity Safe { get; } = new ContentFilterSeverity(SafeValue); + /// + /// Content that expresses prejudiced, judgmental, or opinionated views, includes offensive + /// use of language, stereotyping, use cases exploring a fictional world (for example, gaming, + /// literature) and depictions at low intensity. + /// public static ContentFilterSeverity Low { get; } = new ContentFilterSeverity(LowValue); - - /// Gets the Medium. + /// + /// Content that uses offensive, insulting, mocking, intimidating, or demeaning language + /// towards specific identity groups, includes depictions of seeking and executing harmful + /// instructions, fantasies, glorification, promotion of harm at medium intensity. + /// public static ContentFilterSeverity Medium { get; } = new ContentFilterSeverity(MediumValue); - - /// Gets the High. + /// + /// Content that displays explicit and severe harmful instructions, actions, + /// damage, or abuse; includes endorsement, glorification, or promotion of severe + /// harmful acts, extreme or illegal forms of harm, radicalization, or non-consensual + /// power exchange or abuse. + /// public static ContentFilterSeverity High { get; } = new ContentFilterSeverity(HighValue); - /// Determines if two values are the same. - /// The left value to compare. - /// The right value to compare. public static bool operator ==(ContentFilterSeverity left, ContentFilterSeverity right) => left.Equals(right); - /// Determines if two values are not the same. - /// The left value to compare. - /// The right value to compare. public static bool operator !=(ContentFilterSeverity left, ContentFilterSeverity right) => !left.Equals(right); - - /// Converts a string to a . - /// The value. + /// Converts a to a . public static implicit operator ContentFilterSeverity(string value) => new ContentFilterSeverity(value); - /// The object to compare. + /// [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is ContentFilterSeverity other && Equals(other); - - /// The instance to compare. + /// public bool Equals(ContentFilterSeverity other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - /// + /// [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - - /// + /// public override string ToString() => _value; } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.Serialization.cs new file mode 100644 index 000000000000..d5c884550824 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.Serialization.cs @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class CreateUploadRequest : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateUploadRequest)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + writer.WritePropertyName("mime_type"u8); + writer.WriteStringValue(MimeType); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + CreateUploadRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(CreateUploadRequest)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeCreateUploadRequest(document.RootElement, options); + } + + internal static CreateUploadRequest DeserializeCreateUploadRequest(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string filename = default; + CreateUploadRequestPurpose purpose = default; + int bytes = default; + string mimeType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new CreateUploadRequestPurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("mime_type"u8)) + { + mimeType = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new CreateUploadRequest(filename, purpose, bytes, mimeType, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(CreateUploadRequest)} does not support writing '{options.Format}' format."); + } + } + + CreateUploadRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateUploadRequest(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(CreateUploadRequest)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static CreateUploadRequest FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeCreateUploadRequest(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.cs new file mode 100644 index 000000000000..a48d33b00bf1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequest.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The request body of an upload creation operation. + public partial class CreateUploadRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the file to upload. + /// + /// The intended purpose of the uploaded file. + /// + /// Use 'assistants' for Assistants and Message files, 'vision' for Assistants image file inputs, 'batch' for Batch API, and 'fine-tune' for Fine-tuning. + /// + /// The number of bytes in the file you are uploading. + /// + /// The MIME type of the file. + /// + /// This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + /// + /// or is null. + public CreateUploadRequest(string filename, CreateUploadRequestPurpose purpose, int bytes, string mimeType) + { + Argument.AssertNotNull(filename, nameof(filename)); + Argument.AssertNotNull(mimeType, nameof(mimeType)); + + Filename = filename; + Purpose = purpose; + Bytes = bytes; + MimeType = mimeType; + } + + /// Initializes a new instance of . + /// The name of the file to upload. + /// + /// The intended purpose of the uploaded file. + /// + /// Use 'assistants' for Assistants and Message files, 'vision' for Assistants image file inputs, 'batch' for Batch API, and 'fine-tune' for Fine-tuning. + /// + /// The number of bytes in the file you are uploading. + /// + /// The MIME type of the file. + /// + /// This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + /// + /// Keeps track of any properties unknown to the library. + internal CreateUploadRequest(string filename, CreateUploadRequestPurpose purpose, int bytes, string mimeType, IDictionary serializedAdditionalRawData) + { + Filename = filename; + Purpose = purpose; + Bytes = bytes; + MimeType = mimeType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal CreateUploadRequest() + { + } + + /// The name of the file to upload. + public string Filename { get; } + /// + /// The intended purpose of the uploaded file. + /// + /// Use 'assistants' for Assistants and Message files, 'vision' for Assistants image file inputs, 'batch' for Batch API, and 'fine-tune' for Fine-tuning. + /// + public CreateUploadRequestPurpose Purpose { get; } + /// The number of bytes in the file you are uploading. + public int Bytes { get; } + /// + /// The MIME type of the file. + /// + /// This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision. + /// + public string MimeType { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequestPurpose.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequestPurpose.cs new file mode 100644 index 000000000000..c729a2f7df13 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/CreateUploadRequestPurpose.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The CreateUploadRequestPurpose. + public readonly partial struct CreateUploadRequestPurpose : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public CreateUploadRequestPurpose(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AssistantsValue = "assistants"; + private const string BatchValue = "batch"; + private const string FineTuneValue = "fine-tune"; + private const string VisionValue = "vision"; + + /// assistants. + public static CreateUploadRequestPurpose Assistants { get; } = new CreateUploadRequestPurpose(AssistantsValue); + /// batch. + public static CreateUploadRequestPurpose Batch { get; } = new CreateUploadRequestPurpose(BatchValue); + /// fine-tune. + public static CreateUploadRequestPurpose FineTune { get; } = new CreateUploadRequestPurpose(FineTuneValue); + /// vision. + public static CreateUploadRequestPurpose Vision { get; } = new CreateUploadRequestPurpose(VisionValue); + /// Determines if two values are the same. + public static bool operator ==(CreateUploadRequestPurpose left, CreateUploadRequestPurpose right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(CreateUploadRequestPurpose left, CreateUploadRequestPurpose right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator CreateUploadRequestPurpose(string value) => new CreateUploadRequestPurpose(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is CreateUploadRequestPurpose other && Equals(other); + /// + public bool Equals(CreateUploadRequestPurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..9801e64a18c3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ElasticsearchChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + } + + ElasticsearchChatExtensionConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeElasticsearchChatExtensionConfiguration(document.RootElement, options); + } + + internal static ElasticsearchChatExtensionConfiguration DeserializeElasticsearchChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ElasticsearchChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = ElasticsearchChatExtensionParameters.DeserializeElasticsearchChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ElasticsearchChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + ElasticsearchChatExtensionConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeElasticsearchChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new ElasticsearchChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeElasticsearchChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.cs new file mode 100644 index 000000000000..c02c027fb162 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Elasticsearch when using it as an Azure OpenAI chat + /// extension. + /// + public partial class ElasticsearchChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Elasticsearch®. + /// is null. + public ElasticsearchChatExtensionConfiguration(ElasticsearchChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.Elasticsearch; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Elasticsearch®. + internal ElasticsearchChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, ElasticsearchChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal ElasticsearchChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Elasticsearch®. + public ElasticsearchChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.Serialization.cs new file mode 100644 index 000000000000..509295acf61a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.Serialization.cs @@ -0,0 +1,323 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ElasticsearchChatExtensionParameters : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(DocumentCount)) + { + writer.WritePropertyName("top_n_documents"u8); + writer.WriteNumberValue(DocumentCount.Value); + } + if (Optional.IsDefined(ShouldRestrictResultScope)) + { + writer.WritePropertyName("in_scope"u8); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); + } + if (Optional.IsDefined(Strictness)) + { + writer.WritePropertyName("strictness"u8); + writer.WriteNumberValue(Strictness.Value); + } + if (Optional.IsDefined(MaxSearchQueries)) + { + writer.WritePropertyName("max_search_queries"u8); + writer.WriteNumberValue(MaxSearchQueries.Value); + } + if (Optional.IsDefined(AllowPartialResult)) + { + writer.WritePropertyName("allow_partial_result"u8); + writer.WriteBooleanValue(AllowPartialResult.Value); + } + if (Optional.IsCollectionDefined(IncludeContexts)) + { + writer.WritePropertyName("include_contexts"u8); + writer.WriteStartArray(); + foreach (var item in IncludeContexts) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Authentication)) + { + writer.WritePropertyName("authentication"u8); + writer.WriteObjectValue(Authentication, options); + } + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint.AbsoluteUri); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + if (Optional.IsDefined(FieldMappingOptions)) + { + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldMappingOptions, options); + } + if (Optional.IsDefined(QueryType)) + { + writer.WritePropertyName("query_type"u8); + writer.WriteStringValue(QueryType.Value.ToString()); + } + if (Optional.IsDefined(EmbeddingDependency)) + { + writer.WritePropertyName("embedding_dependency"u8); + writer.WriteObjectValue(EmbeddingDependency, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ElasticsearchChatExtensionParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeElasticsearchChatExtensionParameters(document.RootElement, options); + } + + internal static ElasticsearchChatExtensionParameters DeserializeElasticsearchChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? topNDocuments = default; + bool? inScope = default; + int? strictness = default; + int? maxSearchQueries = default; + bool? allowPartialResult = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; + Uri endpoint = default; + string indexName = default; + ElasticsearchIndexFieldMappingOptions fieldsMapping = default; + ElasticsearchQueryType? queryType = default; + OnYourDataVectorizationSource embeddingDependency = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("top_n_documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topNDocuments = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("in_scope"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inScope = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("strictness"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + strictness = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_search_queries"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxSearchQueries = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("allow_partial_result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + allowPartialResult = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("include_contexts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new OnYourDataContextProperty(item.GetString())); + } + includeContexts = array; + continue; + } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); + continue; + } + if (property.NameEquals("endpoint"u8)) + { + endpoint = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("index_name"u8)) + { + indexName = property.Value.GetString(); + continue; + } + if (property.NameEquals("fields_mapping"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + fieldsMapping = ElasticsearchIndexFieldMappingOptions.DeserializeElasticsearchIndexFieldMappingOptions(property.Value, options); + continue; + } + if (property.NameEquals("query_type"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + queryType = new ElasticsearchQueryType(property.Value.GetString()); + continue; + } + if (property.NameEquals("embedding_dependency"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ElasticsearchChatExtensionParameters( + topNDocuments, + inScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts ?? new ChangeTrackingList(), + authentication, + endpoint, + indexName, + fieldsMapping, + queryType, + embeddingDependency, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support writing '{options.Format}' format."); + } + } + + ElasticsearchChatExtensionParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeElasticsearchChatExtensionParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ElasticsearchChatExtensionParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ElasticsearchChatExtensionParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeElasticsearchChatExtensionParameters(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.cs new file mode 100644 index 000000000000..ce7080e5d85f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchChatExtensionParameters.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters to use when configuring Elasticsearch® as an Azure OpenAI chat extension. The supported authentication types are KeyAndKeyId and EncodedAPIKey. + public partial class ElasticsearchChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The endpoint of Elasticsearch®. + /// The index name of Elasticsearch®. + /// or is null. + public ElasticsearchChatExtensionParameters(Uri endpoint, string indexName) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(indexName, nameof(indexName)); + + IncludeContexts = new ChangeTrackingList(); + Endpoint = endpoint; + IndexName = indexName; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The endpoint of Elasticsearch®. + /// The index name of Elasticsearch®. + /// The index field mapping options of Elasticsearch®. + /// The query type of Elasticsearch®. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal ElasticsearchChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, Uri endpoint, string indexName, ElasticsearchIndexFieldMappingOptions fieldMappingOptions, ElasticsearchQueryType? queryType, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + Endpoint = endpoint; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + QueryType = queryType; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ElasticsearchChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The endpoint of Elasticsearch®. + public Uri Endpoint { get; } + /// The index name of Elasticsearch®. + public string IndexName { get; } + /// The index field mapping options of Elasticsearch®. + public ElasticsearchIndexFieldMappingOptions FieldMappingOptions { get; set; } + /// The query type of Elasticsearch®. + public ElasticsearchQueryType? QueryType { get; set; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.Serialization.cs new file mode 100644 index 000000000000..3a20f3afe3b7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.Serialization.cs @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ElasticsearchIndexFieldMappingOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ElasticsearchIndexFieldMappingOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(TitleFieldName)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleFieldName); + } + if (Optional.IsDefined(UrlFieldName)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlFieldName); + } + if (Optional.IsDefined(FilepathFieldName)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathFieldName); + } + if (Optional.IsCollectionDefined(ContentFieldNames)) + { + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(ContentFieldSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldSeparator); + } + if (Optional.IsCollectionDefined(VectorFieldNames)) + { + writer.WritePropertyName("vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in VectorFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ElasticsearchIndexFieldMappingOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ElasticsearchIndexFieldMappingOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeElasticsearchIndexFieldMappingOptions(document.RootElement, options); + } + + internal static ElasticsearchIndexFieldMappingOptions DeserializeElasticsearchIndexFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string titleField = default; + string urlField = default; + string filepathField = default; + IList contentFields = default; + string contentFieldsSeparator = default; + IList vectorFields = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (property.NameEquals("vector_fields"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorFields = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ElasticsearchIndexFieldMappingOptions( + titleField, + urlField, + filepathField, + contentFields ?? new ChangeTrackingList(), + contentFieldsSeparator, + vectorFields ?? new ChangeTrackingList(), + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ElasticsearchIndexFieldMappingOptions)} does not support writing '{options.Format}' format."); + } + } + + ElasticsearchIndexFieldMappingOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeElasticsearchIndexFieldMappingOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ElasticsearchIndexFieldMappingOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ElasticsearchIndexFieldMappingOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeElasticsearchIndexFieldMappingOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.cs new file mode 100644 index 000000000000..6213ad25cb49 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchIndexFieldMappingOptions.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Optional settings to control how fields are processed when using a configured Elasticsearch® resource. + public partial class ElasticsearchIndexFieldMappingOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public ElasticsearchIndexFieldMappingOptions() + { + ContentFieldNames = new ChangeTrackingList(); + VectorFieldNames = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The name of the index field to use as a title. + /// The name of the index field to use as a URL. + /// The name of the index field to use as a filepath. + /// The names of index fields that should be treated as content. + /// The separator pattern that content fields should use. + /// The names of fields that represent vector data. + /// Keeps track of any properties unknown to the library. + internal ElasticsearchIndexFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IDictionary serializedAdditionalRawData) + { + TitleFieldName = titleFieldName; + UrlFieldName = urlFieldName; + FilepathFieldName = filepathFieldName; + ContentFieldNames = contentFieldNames; + ContentFieldSeparator = contentFieldSeparator; + VectorFieldNames = vectorFieldNames; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + /// The names of fields that represent vector data. + public IList VectorFieldNames { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchQueryType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchQueryType.cs new file mode 100644 index 000000000000..d8588a637f6d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ElasticsearchQueryType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The type of Elasticsearch® retrieval query that should be executed when using it as an Azure OpenAI chat extension. + public readonly partial struct ElasticsearchQueryType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ElasticsearchQueryType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string SimpleValue = "simple"; + private const string VectorValue = "vector"; + + /// Represents the default, simple query parser. + public static ElasticsearchQueryType Simple { get; } = new ElasticsearchQueryType(SimpleValue); + /// Represents vector search over computed data. + public static ElasticsearchQueryType Vector { get; } = new ElasticsearchQueryType(VectorValue); + /// Determines if two values are the same. + public static bool operator ==(ElasticsearchQueryType left, ElasticsearchQueryType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ElasticsearchQueryType left, ElasticsearchQueryType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ElasticsearchQueryType(string value) => new ElasticsearchQueryType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ElasticsearchQueryType other && Equals(other); + /// + public bool Equals(ElasticsearchQueryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingEncodingFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingEncodingFormat.cs new file mode 100644 index 000000000000..213af80cfdb5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingEncodingFormat.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Represents the available formats for embeddings data on responses. + public readonly partial struct EmbeddingEncodingFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public EmbeddingEncodingFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FloatValue = "float"; + private const string Base64Value = "base64"; + + /// Specifies that responses should provide arrays of floats for each embedding. + public static EmbeddingEncodingFormat Float { get; } = new EmbeddingEncodingFormat(FloatValue); + /// Specifies that responses should provide a base64-encoded string for each embedding. + public static EmbeddingEncodingFormat Base64 { get; } = new EmbeddingEncodingFormat(Base64Value); + /// Determines if two values are the same. + public static bool operator ==(EmbeddingEncodingFormat left, EmbeddingEncodingFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(EmbeddingEncodingFormat left, EmbeddingEncodingFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator EmbeddingEncodingFormat(string value) => new EmbeddingEncodingFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is EmbeddingEncodingFormat other && Equals(other); + /// + public bool Equals(EmbeddingEncodingFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.Serialization.cs similarity index 63% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.Serialization.cs index 7f2c64263ba9..0e98c2ab598a 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - public partial class AssistantFile : IUtf8JsonSerializable, IJsonModel + internal partial class EmbeddingItem : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,20 +28,23 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOpt /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AssistantFile)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support writing '{format}' format."); } - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); + writer.WritePropertyName("embedding"u8); + writer.WriteStartArray(); + foreach (var item in Embedding) + { + writer.WriteNumberValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("index"u8); + writer.WriteNumberValue(Index); writer.WritePropertyName("object"u8); - writer.WriteStringValue(Object); - writer.WritePropertyName("created_at"u8); - writer.WriteNumberValue(CreatedAt, "U"); - writer.WritePropertyName("assistant_id"u8); - writer.WriteStringValue(AssistantId); + writer.WriteStringValue(Object.ToString()); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -59,19 +62,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - AssistantFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + EmbeddingItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(AssistantFile)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAssistantFile(document.RootElement, options); + return DeserializeEmbeddingItem(document.RootElement, options); } - internal static AssistantFile DeserializeAssistantFile(JsonElement element, ModelReaderWriterOptions options = null) + internal static EmbeddingItem DeserializeEmbeddingItem(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -79,32 +82,31 @@ internal static AssistantFile DeserializeAssistantFile(JsonElement element, Mode { return null; } - string id = default; - string @object = default; - DateTimeOffset createdAt = default; - string assistantId = default; + IReadOnlyList embedding = default; + int index = default; + EmbeddingItemObject @object = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("embedding"u8)) { - id = property.Value.GetString(); - continue; - } - if (property.NameEquals("object"u8)) - { - @object = property.Value.GetString(); + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetSingle()); + } + embedding = array; continue; } - if (property.NameEquals("created_at"u8)) + if (property.NameEquals("index"u8)) { - createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + index = property.Value.GetInt32(); continue; } - if (property.NameEquals("assistant_id"u8)) + if (property.NameEquals("object"u8)) { - assistantId = property.Value.GetString(); + @object = new EmbeddingItemObject(property.Value.GetString()); continue; } if (options.Format != "W") @@ -113,46 +115,46 @@ internal static AssistantFile DeserializeAssistantFile(JsonElement element, Mode } } serializedAdditionalRawData = rawDataDictionary; - return new AssistantFile(id, @object, createdAt, assistantId, serializedAdditionalRawData); + return new EmbeddingItem(embedding, index, @object, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(AssistantFile)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support writing '{options.Format}' format."); } } - AssistantFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + EmbeddingItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAssistantFile(document.RootElement, options); + return DeserializeEmbeddingItem(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(AssistantFile)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(EmbeddingItem)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static AssistantFile FromResponse(Response response) + internal static EmbeddingItem FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeAssistantFile(document.RootElement); + return DeserializeEmbeddingItem(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.cs new file mode 100644 index 000000000000..047042d2c0f5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItem.cs @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Representation of a single embeddings relatedness comparison. + internal partial class EmbeddingItem + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// List of embeddings value for the input prompt. These represent a measurement of the + /// vector-based relatedness of the provided input. + /// + /// Index of the prompt to which the EmbeddingItem corresponds. + /// is null. + internal EmbeddingItem(IEnumerable embedding, int index) + { + Argument.AssertNotNull(embedding, nameof(embedding)); + + Embedding = embedding.ToList(); + Index = index; + } + + /// Initializes a new instance of . + /// + /// List of embeddings value for the input prompt. These represent a measurement of the + /// vector-based relatedness of the provided input. + /// + /// Index of the prompt to which the EmbeddingItem corresponds. + /// The object type which is always 'embedding'. + /// Keeps track of any properties unknown to the library. + internal EmbeddingItem(IReadOnlyList embedding, int index, EmbeddingItemObject @object, IDictionary serializedAdditionalRawData) + { + Embedding = embedding; + Index = index; + Object = @object; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmbeddingItem() + { + } + + /// + /// List of embeddings value for the input prompt. These represent a measurement of the + /// vector-based relatedness of the provided input. + /// + public IReadOnlyList Embedding { get; } + /// Index of the prompt to which the EmbeddingItem corresponds. + public int Index { get; } + /// The object type which is always 'embedding'. + public EmbeddingItemObject Object { get; } = EmbeddingItemObject.Embedding; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItemObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItemObject.cs new file mode 100644 index 000000000000..6d8867c0c41e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingItemObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The EmbeddingItem_object. + internal readonly partial struct EmbeddingItemObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public EmbeddingItemObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EmbeddingValue = "embedding"; + + /// embedding. + public static EmbeddingItemObject Embedding { get; } = new EmbeddingItemObject(EmbeddingValue); + /// Determines if two values are the same. + public static bool operator ==(EmbeddingItemObject left, EmbeddingItemObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(EmbeddingItemObject left, EmbeddingItemObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator EmbeddingItemObject(string value) => new EmbeddingItemObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is EmbeddingItemObject other && Equals(other); + /// + public bool Equals(EmbeddingItemObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.Serialization.cs new file mode 100644 index 000000000000..8390216076d5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class Embeddings : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAI.Embeddings)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + writer.WritePropertyName("usage"u8); + writer.WriteObjectValue(Usage, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OpenAI.Embeddings IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAI.Embeddings)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return OpenAI.Embeddings.DeserializeEmbeddings(document.RootElement, options); + } + + internal static OpenAI.Embeddings DeserializeEmbeddings(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IReadOnlyList data = default; + EmbeddingsUsage usage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(EmbeddingItem.DeserializeEmbeddingItem(item, options)); + } + data = array; + continue; + } + if (property.NameEquals("usage"u8)) + { + usage = EmbeddingsUsage.DeserializeEmbeddingsUsage(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAI.Embeddings(data, usage, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OpenAI.Embeddings)} does not support writing '{options.Format}' format."); + } + } + + OpenAI.Embeddings IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return OpenAI.Embeddings.DeserializeEmbeddings(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAI.Embeddings)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAI.Embeddings FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return OpenAI.Embeddings.DeserializeEmbeddings(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.cs new file mode 100644 index 000000000000..f6c3403bd45e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Embeddings.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.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. + /// + internal partial class Embeddings + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Embedding values for the prompts submitted in the request. + /// Usage counts for tokens input using the embeddings API. + /// or is null. + internal Embeddings(IEnumerable data, EmbeddingsUsage usage) + { + Argument.AssertNotNull(data, nameof(data)); + Argument.AssertNotNull(usage, nameof(usage)); + + Data = data.ToList(); + Usage = usage; + } + + /// Initializes a new instance of . + /// Embedding values for the prompts submitted in the request. + /// Usage counts for tokens input using the embeddings API. + /// Keeps track of any properties unknown to the library. + internal Embeddings(IReadOnlyList data, EmbeddingsUsage usage, IDictionary serializedAdditionalRawData) + { + Data = data; + Usage = usage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Embeddings() + { + } + + /// Embedding values for the prompts submitted in the request. + public IReadOnlyList Data { get; } + /// Usage counts for tokens input using the embeddings API. + public EmbeddingsUsage Usage { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.Serialization.cs new file mode 100644 index 000000000000..da4e24a9d382 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.Serialization.cs @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class EmbeddingsOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmbeddingsOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + writer.WritePropertyName("input"u8); + writer.WriteStartArray(); + foreach (var item in Input) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(EncodingFormat)) + { + writer.WritePropertyName("encoding_format"u8); + writer.WriteStringValue(EncodingFormat.Value.ToString()); + } + if (Optional.IsDefined(Dimensions)) + { + writer.WritePropertyName("dimensions"u8); + writer.WriteNumberValue(Dimensions.Value); + } + if (Optional.IsDefined(InputType)) + { + writer.WritePropertyName("input_type"u8); + writer.WriteStringValue(InputType); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + EmbeddingsOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmbeddingsOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmbeddingsOptions(document.RootElement, options); + } + + internal static EmbeddingsOptions DeserializeEmbeddingsOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string user = default; + string model = default; + IList input = default; + EmbeddingEncodingFormat? encodingFormat = default; + int? dimensions = default; + string inputType = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("input"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + input = array; + continue; + } + if (property.NameEquals("encoding_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + encodingFormat = new EmbeddingEncodingFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("dimensions"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dimensions = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("input_type"u8)) + { + inputType = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmbeddingsOptions( + user, + model, + input, + encodingFormat, + dimensions, + inputType, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(EmbeddingsOptions)} does not support writing '{options.Format}' format."); + } + } + + EmbeddingsOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmbeddingsOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmbeddingsOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static EmbeddingsOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmbeddingsOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.cs new file mode 100644 index 000000000000..7a25f39f4f5a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsOptions.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class EmbeddingsOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// 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. + /// + /// is null. + public EmbeddingsOptions(IEnumerable input) + { + Argument.AssertNotNull(input, nameof(input)); + + Input = input.ToList(); + } + + /// Initializes a new instance of . + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + /// + /// 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. + /// + /// + /// 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 response encoding format to use for embedding data. + /// The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. + /// When using Azure OpenAI, specifies the input type to use for embedding search. + /// Keeps track of any properties unknown to the library. + internal EmbeddingsOptions(string user, string deploymentName, IList input, EmbeddingEncodingFormat? encodingFormat, int? dimensions, string inputType, IDictionary serializedAdditionalRawData) + { + User = user; + DeploymentName = deploymentName; + Input = input; + EncodingFormat = encodingFormat; + Dimensions = dimensions; + InputType = inputType; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmbeddingsOptions() + { + } + + /// + /// An identifier for the caller or end user of the operation. This may be used for tracking + /// or rate-limiting purposes. + /// + public string User { get; set; } + /// + /// 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. + /// + public string DeploymentName { get; set; } + /// + /// 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. + /// + public IList Input { get; } + /// The response encoding format to use for embedding data. + public EmbeddingEncodingFormat? EncodingFormat { get; set; } + /// The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. + public int? Dimensions { get; set; } + /// When using Azure OpenAI, specifies the input type to use for embedding search. + public string InputType { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.Serialization.cs new file mode 100644 index 000000000000..6060c19f5fc1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class EmbeddingsUsage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmbeddingsUsage)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("prompt_tokens"u8); + writer.WriteNumberValue(PromptTokens); + writer.WritePropertyName("total_tokens"u8); + writer.WriteNumberValue(TotalTokens); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + EmbeddingsUsage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(EmbeddingsUsage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeEmbeddingsUsage(document.RootElement, options); + } + + internal static EmbeddingsUsage DeserializeEmbeddingsUsage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int promptTokens = default; + int totalTokens = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("prompt_tokens"u8)) + { + promptTokens = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("total_tokens"u8)) + { + totalTokens = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new EmbeddingsUsage(promptTokens, totalTokens, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(EmbeddingsUsage)} does not support writing '{options.Format}' format."); + } + } + + EmbeddingsUsage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmbeddingsUsage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(EmbeddingsUsage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static EmbeddingsUsage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeEmbeddingsUsage(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.cs new file mode 100644 index 000000000000..00f0ce06d636 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/EmbeddingsUsage.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Measurement of the amount of tokens used in this request and response. + internal partial class EmbeddingsUsage + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Number of tokens sent in the original request. + /// Total number of tokens transacted in this request/response. + internal EmbeddingsUsage(int promptTokens, int totalTokens) + { + PromptTokens = promptTokens; + TotalTokens = totalTokens; + } + + /// Initializes a new instance of . + /// Number of tokens sent in the original request. + /// Total number of tokens transacted in this request/response. + /// Keeps track of any properties unknown to the library. + internal EmbeddingsUsage(int promptTokens, int totalTokens, IDictionary serializedAdditionalRawData) + { + PromptTokens = promptTokens; + TotalTokens = totalTokens; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal EmbeddingsUsage() + { + } + + /// Number of tokens sent in the original request. + public int PromptTokens { get; } + /// Total number of tokens transacted in this request/response. + public int TotalTokens { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.Serialization.cs new file mode 100644 index 000000000000..fc5521a8e57c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.Serialization.cs @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FileDeletionStatus : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileDeletionStatus)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("deleted"u8); + writer.WriteBooleanValue(Deleted); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FileDeletionStatus IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileDeletionStatus)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileDeletionStatus(document.RootElement, options); + } + + internal static FileDeletionStatus DeserializeFileDeletionStatus(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + bool deleted = default; + FileDeletionStatusObject @object = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("deleted"u8)) + { + deleted = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new FileDeletionStatusObject(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileDeletionStatus(id, deleted, @object, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FileDeletionStatus)} does not support writing '{options.Format}' format."); + } + } + + FileDeletionStatus IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileDeletionStatus(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileDeletionStatus)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileDeletionStatus FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileDeletionStatus(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.cs new file mode 100644 index 000000000000..1ffbf9b3ebf9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatus.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A status response from a file deletion operation. + public partial class FileDeletionStatus + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// is null. + internal FileDeletionStatus(string id, bool deleted) + { + Argument.AssertNotNull(id, nameof(id)); + + Id = id; + Deleted = deleted; + } + + /// Initializes a new instance of . + /// The ID of the resource specified for deletion. + /// A value indicating whether deletion was successful. + /// The object type, which is always 'file'. + /// Keeps track of any properties unknown to the library. + internal FileDeletionStatus(string id, bool deleted, FileDeletionStatusObject @object, IDictionary serializedAdditionalRawData) + { + Id = id; + Deleted = deleted; + Object = @object; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FileDeletionStatus() + { + } + + /// The ID of the resource specified for deletion. + public string Id { get; } + /// A value indicating whether deletion was successful. + public bool Deleted { get; } + /// The object type, which is always 'file'. + public FileDeletionStatusObject Object { get; } = FileDeletionStatusObject.File; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatusObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatusObject.cs new file mode 100644 index 000000000000..7023f72b90f5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileDeletionStatusObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The FileDeletionStatus_object. + public readonly partial struct FileDeletionStatusObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileDeletionStatusObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FileValue = "file"; + + /// file. + public static FileDeletionStatusObject File { get; } = new FileDeletionStatusObject(FileValue); + /// Determines if two values are the same. + public static bool operator ==(FileDeletionStatusObject left, FileDeletionStatusObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileDeletionStatusObject left, FileDeletionStatusObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileDeletionStatusObject(string value) => new FileDeletionStatusObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileDeletionStatusObject other && Equals(other); + /// + public bool Equals(FileDeletionStatusObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.Serialization.cs new file mode 100644 index 000000000000..7e7313add329 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FileListResponse : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileListResponse)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FileListResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FileListResponse)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFileListResponse(document.RootElement, options); + } + + internal static FileListResponse DeserializeFileListResponse(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + FileListResponseObject @object = default; + IReadOnlyList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new FileListResponseObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(OpenAIFile.DeserializeOpenAIFile(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FileListResponse(@object, data, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FileListResponse)} does not support writing '{options.Format}' format."); + } + } + + FileListResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileListResponse(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FileListResponse)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FileListResponse FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFileListResponse(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.cs new file mode 100644 index 000000000000..bcd03986f3fc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponse.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The response data from a file list operation. + public partial class FileListResponse + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The files returned for the request. + /// is null. + internal FileListResponse(IEnumerable data) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data.ToList(); + } + + /// Initializes a new instance of . + /// The object type, which is always 'list'. + /// The files returned for the request. + /// Keeps track of any properties unknown to the library. + internal FileListResponse(FileListResponseObject @object, IReadOnlyList data, IDictionary serializedAdditionalRawData) + { + Object = @object; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FileListResponse() + { + } + + /// The object type, which is always 'list'. + public FileListResponseObject Object { get; } = FileListResponseObject.List; + + /// The files returned for the request. + public IReadOnlyList Data { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponseObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponseObject.cs new file mode 100644 index 000000000000..4d72d8c6702d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileListResponseObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The FileListResponse_object. + public readonly partial struct FileListResponseObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileListResponseObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static FileListResponseObject List { get; } = new FileListResponseObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(FileListResponseObject left, FileListResponseObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileListResponseObject left, FileListResponseObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileListResponseObject(string value) => new FileListResponseObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileListResponseObject other && Equals(other); + /// + public bool Equals(FileListResponseObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FilePurpose.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FilePurpose.cs new file mode 100644 index 000000000000..a77cbe48fa1b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FilePurpose.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The possible values denoting the intended usage of a file. + public readonly partial struct FilePurpose : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FilePurpose(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FineTuneValue = "fine-tune"; + private const string FineTuneResultsValue = "fine-tune-results"; + private const string AssistantsValue = "assistants"; + private const string AssistantsOutputValue = "assistants_output"; + private const string BatchValue = "batch"; + private const string BatchOutputValue = "batch_output"; + private const string VisionValue = "vision"; + + /// Indicates a file is used for fine tuning input. + public static FilePurpose FineTune { get; } = new FilePurpose(FineTuneValue); + /// Indicates a file is used for fine tuning results. + public static FilePurpose FineTuneResults { get; } = new FilePurpose(FineTuneResultsValue); + /// Indicates a file is used as input to assistants. + public static FilePurpose Assistants { get; } = new FilePurpose(AssistantsValue); + /// Indicates a file is used as output by assistants. + public static FilePurpose AssistantsOutput { get; } = new FilePurpose(AssistantsOutputValue); + /// Indicates a file is used as input to . + public static FilePurpose Batch { get; } = new FilePurpose(BatchValue); + /// Indicates a file is used as output by a vector store batch operation. + public static FilePurpose BatchOutput { get; } = new FilePurpose(BatchOutputValue); + /// Indicates a file is used as input to a vision operation. + public static FilePurpose Vision { get; } = new FilePurpose(VisionValue); + /// Determines if two values are the same. + public static bool operator ==(FilePurpose left, FilePurpose right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FilePurpose left, FilePurpose right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FilePurpose(string value) => new FilePurpose(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FilePurpose other && Equals(other); + /// + public bool Equals(FilePurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FileState.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileState.cs new file mode 100644 index 000000000000..637802d9dee3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FileState.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The state of the file. + public readonly partial struct FileState : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FileState(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadedValue = "uploaded"; + private const string PendingValue = "pending"; + private const string RunningValue = "running"; + private const string ProcessedValue = "processed"; + private const string ErrorValue = "error"; + private const string DeletingValue = "deleting"; + private const string DeletedValue = "deleted"; + + /// + /// The file has been uploaded but it's not yet processed. This state is not returned by Azure OpenAI and exposed only for + /// compatibility. It can be categorized as an inactive state. + /// + public static FileState Uploaded { get; } = new FileState(UploadedValue); + /// The operation was created and is not queued to be processed in the future. It can be categorized as an inactive state. + public static FileState Pending { get; } = new FileState(PendingValue); + /// The operation has started to be processed. It can be categorized as an active state. + public static FileState Running { get; } = new FileState(RunningValue); + /// The operation has successfully processed and is ready for consumption. It can be categorized as a terminal state. + public static FileState Processed { get; } = new FileState(ProcessedValue); + /// The operation has completed processing with a failure and cannot be further consumed. It can be categorized as a terminal state. + public static FileState Error { get; } = new FileState(ErrorValue); + /// + /// The entity is in the process to be deleted. This state is not returned by Azure OpenAI and exposed only for compatibility. + /// It can be categorized as an active state. + /// + public static FileState Deleting { get; } = new FileState(DeletingValue); + /// + /// The entity has been deleted but may still be referenced by other entities predating the deletion. It can be categorized as a + /// terminal state. + /// + public static FileState Deleted { get; } = new FileState(DeletedValue); + /// Determines if two values are the same. + public static bool operator ==(FileState left, FileState right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FileState left, FileState right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FileState(string value) => new FileState(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FileState other && Equals(other); + /// + public bool Equals(FileState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.Serialization.cs new file mode 100644 index 000000000000..7ad98ae50761 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FunctionCall : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionCall)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + writer.WritePropertyName("arguments"u8); + writer.WriteStringValue(Arguments); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FunctionCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionCall)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionCall(document.RootElement, options); + } + + internal static FunctionCall DeserializeFunctionCall(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string arguments = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("arguments"u8)) + { + arguments = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionCall(name, arguments, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FunctionCall)} does not support writing '{options.Format}' format."); + } + } + + FunctionCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionCall(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionCall)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionCall FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionCall(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.cs new file mode 100644 index 000000000000..2a2534aebe1e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCall.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The name and arguments of a function that should be called, as generated by the model. + public partial class FunctionCall + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to call. + /// + /// The arguments to call the function with, as generated by the model in JSON format. + /// Note that the model does not always generate valid JSON, and may hallucinate parameters + /// not defined by your function schema. Validate the arguments in your code before calling + /// your function. + /// + /// or is null. + public FunctionCall(string name, string arguments) + { + Argument.AssertNotNull(name, nameof(name)); + Argument.AssertNotNull(arguments, nameof(arguments)); + + Name = name; + Arguments = arguments; + } + + /// Initializes a new instance of . + /// The name of the function to call. + /// + /// The arguments to call the function with, as generated by the model in JSON format. + /// Note that the model does not always generate valid JSON, and may hallucinate parameters + /// not defined by your function schema. Validate the arguments in your code before calling + /// your function. + /// + /// Keeps track of any properties unknown to the library. + internal FunctionCall(string name, string arguments, IDictionary serializedAdditionalRawData) + { + Name = name; + Arguments = arguments; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionCall() + { + } + + /// The name of the function to call. + public string Name { get; set; } + /// + /// The arguments to call the function with, as generated by the model in JSON format. + /// Note that the model does not always generate valid JSON, and may hallucinate parameters + /// not defined by your function schema. Validate the arguments in your code before calling + /// your function. + /// + public string Arguments { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCallPreset.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCallPreset.cs new file mode 100644 index 000000000000..6e15f0039916 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionCallPreset.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// The collection of predefined behaviors for handling request-provided function information in a chat completions + /// operation. + /// + public readonly partial struct FunctionCallPreset : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public FunctionCallPreset(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AutoValue = "auto"; + private const string NoneValue = "none"; + + /// + /// Specifies that the model may either use any of the functions provided in this chat completions request or + /// instead return a standard chat completions response as if no functions were provided. + /// + public static FunctionCallPreset Auto { get; } = new FunctionCallPreset(AutoValue); + /// + /// Specifies that the model should not respond with a function call and should instead provide a standard chat + /// completions response. Response content may still be influenced by the provided function information. + /// + public static FunctionCallPreset None { get; } = new FunctionCallPreset(NoneValue); + /// Determines if two values are the same. + public static bool operator ==(FunctionCallPreset left, FunctionCallPreset right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(FunctionCallPreset left, FunctionCallPreset right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator FunctionCallPreset(string value) => new FunctionCallPreset(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is FunctionCallPreset other && Equals(other); + /// + public bool Equals(FunctionCallPreset other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.Serialization.cs new file mode 100644 index 000000000000..f734f032d231 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.Serialization.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FunctionDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionDefinition)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (Optional.IsDefined(Description)) + { + writer.WritePropertyName("description"u8); + writer.WriteStringValue(Description); + } + if (Optional.IsDefined(Parameters)) + { + writer.WritePropertyName("parameters"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Parameters); +#else + using (JsonDocument document = JsonDocument.Parse(Parameters, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FunctionDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionDefinition(document.RootElement, options); + } + + internal static FunctionDefinition DeserializeFunctionDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + string description = default; + BinaryData parameters = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (property.NameEquals("description"u8)) + { + description = property.Value.GetString(); + continue; + } + if (property.NameEquals("parameters"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + parameters = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionDefinition(name, description, parameters, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FunctionDefinition)} does not support writing '{options.Format}' format."); + } + } + + FunctionDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionDefinition(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.cs new file mode 100644 index 000000000000..1de7bfba323c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionDefinition.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The definition of a caller-specified function that chat completions may invoke in response to matching user input. + public partial class FunctionDefinition + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to be called. + /// is null. + public FunctionDefinition(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// The name of the function to be called. + /// + /// A description of what the function does. The model will use this description when selecting the function and + /// interpreting its parameters. + /// + /// The parameters the function accepts, described as a JSON Schema object. + /// Keeps track of any properties unknown to the library. + internal FunctionDefinition(string name, string description, BinaryData parameters, IDictionary serializedAdditionalRawData) + { + Name = name; + Description = description; + Parameters = parameters; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionDefinition() + { + } + + /// The name of the function to be called. + public string Name { get; } + /// + /// A description of what the function does. The model will use this description when selecting the function and + /// interpreting its parameters. + /// + public string Description { get; set; } + /// + /// The parameters the function accepts, described as a JSON Schema object. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Parameters { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.Serialization.cs new file mode 100644 index 000000000000..d5600b556cc2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class FunctionName : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionName)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("name"u8); + writer.WriteStringValue(Name); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + FunctionName IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(FunctionName)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeFunctionName(document.RootElement, options); + } + + internal static FunctionName DeserializeFunctionName(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string name = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("name"u8)) + { + name = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new FunctionName(name, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(FunctionName)} does not support writing '{options.Format}' format."); + } + } + + FunctionName IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionName(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(FunctionName)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static FunctionName FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeFunctionName(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.cs new file mode 100644 index 000000000000..14ca22fb4973 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/FunctionName.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A structure that specifies the exact name of a specific, request-provided function to use when processing a chat + /// completions operation. + /// + public partial class FunctionName + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the function to call. + /// is null. + public FunctionName(string name) + { + Argument.AssertNotNull(name, nameof(name)); + + Name = name; + } + + /// Initializes a new instance of . + /// The name of the function to call. + /// Keeps track of any properties unknown to the library. + internal FunctionName(string name, IDictionary serializedAdditionalRawData) + { + Name = name; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal FunctionName() + { + } + + /// The name of the function to call. + public string Name { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.Serialization.cs new file mode 100644 index 000000000000..47ed25517498 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.Serialization.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ImageGenerationContentFilterResults : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Sexual)) + { + writer.WritePropertyName("sexual"u8); + writer.WriteObjectValue(Sexual, options); + } + if (Optional.IsDefined(Violence)) + { + writer.WritePropertyName("violence"u8); + writer.WriteObjectValue(Violence, options); + } + if (Optional.IsDefined(Hate)) + { + writer.WritePropertyName("hate"u8); + writer.WriteObjectValue(Hate, options); + } + if (Optional.IsDefined(SelfHarm)) + { + writer.WritePropertyName("self_harm"u8); + writer.WriteObjectValue(SelfHarm, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ImageGenerationContentFilterResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeImageGenerationContentFilterResults(document.RootElement, options); + } + + internal static ImageGenerationContentFilterResults DeserializeImageGenerationContentFilterResults(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sexual"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("violence"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("hate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("self_harm"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ImageGenerationContentFilterResults(sexual, violence, hate, selfHarm, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support writing '{options.Format}' format."); + } + } + + ImageGenerationContentFilterResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerationContentFilterResults(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ImageGenerationContentFilterResults)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ImageGenerationContentFilterResults FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerationContentFilterResults(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.cs new file mode 100644 index 000000000000..a9dd21aaaa9d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationContentFilterResults.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Describes the content filtering result for the image generation request. + public partial class ImageGenerationContentFilterResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ImageGenerationContentFilterResults() + { + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Keeps track of any properties unknown to the library. + internal ImageGenerationContentFilterResults(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// 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. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// 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. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.Serialization.cs similarity index 55% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.Serialization.cs index e86fb126c760..35f5c2abb8be 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/LivenessSessionItem.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI { - public partial class LivenessSessionItem : IUtf8JsonSerializable, IJsonModel + public partial class ImageGenerationData : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,35 +28,36 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWri /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationData)} does not support writing '{format}' format."); } - if (options.Format != "W") + if (Optional.IsDefined(Url)) { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); + writer.WritePropertyName("url"u8); + writer.WriteStringValue(Url.AbsoluteUri); } - writer.WritePropertyName("createdDateTime"u8); - writer.WriteStringValue(CreatedDateTime, "O"); - if (Optional.IsDefined(SessionStartDateTime)) + if (Optional.IsDefined(Base64Data)) { - writer.WritePropertyName("sessionStartDateTime"u8); - writer.WriteStringValue(SessionStartDateTime.Value, "O"); + writer.WritePropertyName("b64_json"u8); + writer.WriteStringValue(Base64Data); } - writer.WritePropertyName("sessionExpired"u8); - writer.WriteBooleanValue(SessionExpired); - if (Optional.IsDefined(DeviceCorrelationId)) + if (Optional.IsDefined(ContentFilterResults)) { - writer.WritePropertyName("deviceCorrelationId"u8); - writer.WriteStringValue(DeviceCorrelationId); + writer.WritePropertyName("content_filter_results"u8); + writer.WriteObjectValue(ContentFilterResults, options); } - if (Optional.IsDefined(AuthTokenTimeToLiveInSeconds)) + if (Optional.IsDefined(RevisedPrompt)) { - writer.WritePropertyName("authTokenTimeToLiveInSeconds"u8); - writer.WriteNumberValue(AuthTokenTimeToLiveInSeconds.Value); + writer.WritePropertyName("revised_prompt"u8); + writer.WriteStringValue(RevisedPrompt); + } + if (Optional.IsDefined(PromptFilterResults)) + { + writer.WritePropertyName("prompt_filter_results"u8); + writer.WriteObjectValue(PromptFilterResults, options); } if (options.Format != "W" && _serializedAdditionalRawData != null) { @@ -75,19 +76,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - LivenessSessionItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ImageGenerationData IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationData)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeLivenessSessionItem(document.RootElement, options); + return DeserializeImageGenerationData(document.RootElement, options); } - internal static LivenessSessionItem DeserializeLivenessSessionItem(JsonElement element, ModelReaderWriterOptions options = null) + internal static ImageGenerationData DeserializeImageGenerationData(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -95,52 +96,50 @@ internal static LivenessSessionItem DeserializeLivenessSessionItem(JsonElement e { return null; } - string id = default; - DateTimeOffset createdDateTime = default; - DateTimeOffset? sessionStartDateTime = default; - bool sessionExpired = default; - string deviceCorrelationId = default; - int? authTokenTimeToLiveInSeconds = default; + Uri url = default; + string b64Json = default; + ImageGenerationContentFilterResults contentFilterResults = default; + string revisedPrompt = default; + ImageGenerationPromptFilterResults promptFilterResults = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("id"u8)) + if (property.NameEquals("url"u8)) { - id = property.Value.GetString(); + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + url = new Uri(property.Value.GetString()); continue; } - if (property.NameEquals("createdDateTime"u8)) + if (property.NameEquals("b64_json"u8)) { - createdDateTime = property.Value.GetDateTimeOffset("O"); + b64Json = property.Value.GetString(); continue; } - if (property.NameEquals("sessionStartDateTime"u8)) + if (property.NameEquals("content_filter_results"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - sessionStartDateTime = property.Value.GetDateTimeOffset("O"); - continue; - } - if (property.NameEquals("sessionExpired"u8)) - { - sessionExpired = property.Value.GetBoolean(); + contentFilterResults = ImageGenerationContentFilterResults.DeserializeImageGenerationContentFilterResults(property.Value, options); continue; } - if (property.NameEquals("deviceCorrelationId"u8)) + if (property.NameEquals("revised_prompt"u8)) { - deviceCorrelationId = property.Value.GetString(); + revisedPrompt = property.Value.GetString(); continue; } - if (property.NameEquals("authTokenTimeToLiveInSeconds"u8)) + if (property.NameEquals("prompt_filter_results"u8)) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } - authTokenTimeToLiveInSeconds = property.Value.GetInt32(); + promptFilterResults = ImageGenerationPromptFilterResults.DeserializeImageGenerationPromptFilterResults(property.Value, options); continue; } if (options.Format != "W") @@ -149,53 +148,52 @@ internal static LivenessSessionItem DeserializeLivenessSessionItem(JsonElement e } } serializedAdditionalRawData = rawDataDictionary; - return new LivenessSessionItem( - id, - createdDateTime, - sessionStartDateTime, - sessionExpired, - deviceCorrelationId, - authTokenTimeToLiveInSeconds, + return new ImageGenerationData( + url, + b64Json, + contentFilterResults, + revisedPrompt, + promptFilterResults, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationData)} does not support writing '{options.Format}' format."); } } - LivenessSessionItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ImageGenerationData IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionItem(document.RootElement, options); + return DeserializeImageGenerationData(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(LivenessSessionItem)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ImageGenerationData)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static LivenessSessionItem FromResponse(Response response) + internal static ImageGenerationData FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeLivenessSessionItem(document.RootElement); + return DeserializeImageGenerationData(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.cs new file mode 100644 index 000000000000..63091f309bba --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationData.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A representation of a single generated image, provided as either base64-encoded data or as a URL from which the image + /// may be retrieved. + /// + public partial class ImageGenerationData + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ImageGenerationData() + { + } + + /// Initializes a new instance of . + /// The URL that provides temporary access to download the generated image. + /// The complete data for an image, represented as a base64-encoded string. + /// Information about the content filtering results. + /// + /// 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. + /// + /// + /// 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. Information about jailbreak content and profanity, if it has been detected, + /// and if it has been filtered or not. And information about customer block list, if it has + /// been filtered and its id. + /// + /// Keeps track of any properties unknown to the library. + internal ImageGenerationData(Uri url, string base64Data, ImageGenerationContentFilterResults contentFilterResults, string revisedPrompt, ImageGenerationPromptFilterResults promptFilterResults, IDictionary serializedAdditionalRawData) + { + Url = url; + Base64Data = base64Data; + ContentFilterResults = contentFilterResults; + RevisedPrompt = revisedPrompt; + PromptFilterResults = promptFilterResults; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The URL that provides temporary access to download the generated image. + public Uri Url { get; } + /// The complete data for an image, represented as a base64-encoded string. + public string Base64Data { get; } + /// Information about the content filtering results. + public ImageGenerationContentFilterResults ContentFilterResults { get; } + /// + /// 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. + /// + public string RevisedPrompt { get; } + /// + /// 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. Information about jailbreak content and profanity, if it has been detected, + /// and if it has been filtered or not. And information about customer block list, if it has + /// been filtered and its id. + /// + public ImageGenerationPromptFilterResults PromptFilterResults { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.Serialization.cs new file mode 100644 index 000000000000..e70139175af5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.Serialization.cs @@ -0,0 +1,248 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ImageGenerationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerationOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + writer.WritePropertyName("prompt"u8); + writer.WriteStringValue(Prompt); + if (Optional.IsDefined(ImageCount)) + { + writer.WritePropertyName("n"u8); + writer.WriteNumberValue(ImageCount.Value); + } + if (Optional.IsDefined(Size)) + { + writer.WritePropertyName("size"u8); + writer.WriteStringValue(Size.Value.ToString()); + } + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Quality)) + { + writer.WritePropertyName("quality"u8); + writer.WriteStringValue(Quality.Value.ToString()); + } + if (Optional.IsDefined(Style)) + { + writer.WritePropertyName("style"u8); + writer.WriteStringValue(Style.Value.ToString()); + } + if (Optional.IsDefined(User)) + { + writer.WritePropertyName("user"u8); + writer.WriteStringValue(User); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ImageGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeImageGenerationOptions(document.RootElement, options); + } + + internal static ImageGenerationOptions DeserializeImageGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string model = default; + string prompt = default; + int? n = default; + ImageSize? size = default; + ImageGenerationResponseFormat? responseFormat = default; + ImageGenerationQuality? quality = default; + ImageGenerationStyle? style = default; + string user = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (property.NameEquals("prompt"u8)) + { + prompt = property.Value.GetString(); + continue; + } + if (property.NameEquals("n"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + n = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("size"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + size = new ImageSize(property.Value.GetString()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new ImageGenerationResponseFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("quality"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + quality = new ImageGenerationQuality(property.Value.GetString()); + continue; + } + if (property.NameEquals("style"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + style = new ImageGenerationStyle(property.Value.GetString()); + continue; + } + if (property.NameEquals("user"u8)) + { + user = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ImageGenerationOptions( + model, + prompt, + n, + size, + responseFormat, + quality, + style, + user, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ImageGenerationOptions)} does not support writing '{options.Format}' format."); + } + } + + ImageGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ImageGenerationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ImageGenerationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.cs new file mode 100644 index 000000000000..d5756901ef45 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationOptions.cs @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the request data used to generate images. + public partial class ImageGenerationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// A description of the desired images. + /// is null. + public ImageGenerationOptions(string prompt) + { + Argument.AssertNotNull(prompt, nameof(prompt)); + + Prompt = prompt; + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// A description of the desired images. + /// + /// 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. + /// + /// + /// The desired dimensions for generated images. + /// Dall-e-2 models support 256x256, 512x512, or 1024x1024. + /// Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. + /// + /// The format in which image generation response items should be presented. + /// + /// The desired image generation quality level to use. + /// Only configurable with dall-e-3 models. + /// + /// + /// The desired image generation style to use. + /// Only configurable with dall-e-3 models. + /// + /// A unique identifier representing your end-user, which can help to monitor and detect abuse. + /// Keeps track of any properties unknown to the library. + internal ImageGenerationOptions(string deploymentName, string prompt, int? imageCount, ImageSize? size, ImageGenerationResponseFormat? responseFormat, ImageGenerationQuality? quality, ImageGenerationStyle? style, string user, IDictionary serializedAdditionalRawData) + { + DeploymentName = deploymentName; + Prompt = prompt; + ImageCount = imageCount; + Size = size; + ResponseFormat = responseFormat; + Quality = quality; + Style = style; + User = user; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal 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. + /// + public string DeploymentName { get; set; } + /// A description of the desired images. + public string Prompt { get; set; } + /// + /// 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. + /// + public int? ImageCount { get; set; } + /// + /// The desired dimensions for generated images. + /// Dall-e-2 models support 256x256, 512x512, or 1024x1024. + /// Dall-e-3 models support 1024x1024, 1792x1024, or 1024x1792. + /// + public ImageSize? Size { get; set; } + /// The format in which image generation response items should be presented. + public ImageGenerationResponseFormat? ResponseFormat { get; set; } + /// + /// The desired image generation quality level to use. + /// Only configurable with dall-e-3 models. + /// + public ImageGenerationQuality? Quality { get; set; } + /// + /// The desired image generation style to use. + /// Only configurable with dall-e-3 models. + /// + public ImageGenerationStyle? Style { get; set; } + /// A unique identifier representing your end-user, which can help to monitor and detect abuse. + public string User { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.Serialization.cs new file mode 100644 index 000000000000..af07c41bd1ca --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.Serialization.cs @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ImageGenerationPromptFilterResults : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Sexual)) + { + writer.WritePropertyName("sexual"u8); + writer.WriteObjectValue(Sexual, options); + } + if (Optional.IsDefined(Violence)) + { + writer.WritePropertyName("violence"u8); + writer.WriteObjectValue(Violence, options); + } + if (Optional.IsDefined(Hate)) + { + writer.WritePropertyName("hate"u8); + writer.WriteObjectValue(Hate, options); + } + if (Optional.IsDefined(SelfHarm)) + { + writer.WritePropertyName("self_harm"u8); + writer.WriteObjectValue(SelfHarm, options); + } + if (Optional.IsDefined(Profanity)) + { + writer.WritePropertyName("profanity"u8); + writer.WriteObjectValue(Profanity, options); + } + if (Optional.IsDefined(Jailbreak)) + { + writer.WritePropertyName("jailbreak"u8); + writer.WriteObjectValue(Jailbreak, options); + } + if (Optional.IsDefined(CustomBlocklists)) + { + writer.WritePropertyName("custom_blocklists"u8); + writer.WriteObjectValue(CustomBlocklists, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ImageGenerationPromptFilterResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeImageGenerationPromptFilterResults(document.RootElement, options); + } + + internal static ImageGenerationPromptFilterResults DeserializeImageGenerationPromptFilterResults(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ContentFilterResult sexual = default; + ContentFilterResult violence = default; + ContentFilterResult hate = default; + ContentFilterResult selfHarm = default; + ContentFilterDetectionResult profanity = default; + ContentFilterDetectionResult jailbreak = default; + ContentFilterDetailedResults customBlocklists = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("sexual"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + sexual = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("violence"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + violence = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("hate"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hate = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("self_harm"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + selfHarm = ContentFilterResult.DeserializeContentFilterResult(property.Value, options); + continue; + } + if (property.NameEquals("profanity"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + continue; + } + if (property.NameEquals("jailbreak"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + jailbreak = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(property.Value, options); + continue; + } + if (property.NameEquals("custom_blocklists"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + customBlocklists = ContentFilterDetailedResults.DeserializeContentFilterDetailedResults(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ImageGenerationPromptFilterResults( + sexual, + violence, + hate, + selfHarm, + profanity, + jailbreak, + customBlocklists, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support writing '{options.Format}' format."); + } + } + + ImageGenerationPromptFilterResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerationPromptFilterResults(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ImageGenerationPromptFilterResults)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ImageGenerationPromptFilterResults FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerationPromptFilterResults(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.cs new file mode 100644 index 000000000000..e66c52bc7c1f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationPromptFilterResults.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Describes the content filtering results for the prompt of a image generation request. + public partial class ImageGenerationPromptFilterResults + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal ImageGenerationPromptFilterResults() + { + } + + /// Initializes a new instance of . + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + /// + /// 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. + /// + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + /// Describes whether profanity was detected. + /// Whether a jailbreak attempt was detected in the prompt. + /// Information about customer block lists and if something was detected the associated list ID. + /// Keeps track of any properties unknown to the library. + internal ImageGenerationPromptFilterResults(ContentFilterResult sexual, ContentFilterResult violence, ContentFilterResult hate, ContentFilterResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterDetectionResult jailbreak, ContentFilterDetailedResults customBlocklists, IDictionary serializedAdditionalRawData) + { + Sexual = sexual; + Violence = violence; + Hate = hate; + SelfHarm = selfHarm; + Profanity = profanity; + Jailbreak = jailbreak; + CustomBlocklists = customBlocklists; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// + /// 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. + /// + public ContentFilterResult Sexual { get; } + /// + /// Describes language related to physical actions intended to hurt, injure, damage, or + /// kill someone or something; describes weapons, etc. + /// + public ContentFilterResult Violence { get; } + /// + /// 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. + /// + public ContentFilterResult Hate { get; } + /// + /// Describes language related to physical actions intended to purposely hurt, injure, + /// or damage one’s body, or kill oneself. + /// + public ContentFilterResult SelfHarm { get; } + /// Describes whether profanity was detected. + public ContentFilterDetectionResult Profanity { get; } + /// Whether a jailbreak attempt was detected in the prompt. + public ContentFilterDetectionResult Jailbreak { get; } + /// Information about customer block lists and if something was detected the associated list ID. + public ContentFilterDetailedResults CustomBlocklists { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationQuality.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationQuality.cs new file mode 100644 index 000000000000..31d282d1a6db --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationQuality.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// An image generation configuration that specifies how the model should prioritize quality, cost, and speed. + /// Only configurable with dall-e-3 models. + /// + public readonly partial struct ImageGenerationQuality : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageGenerationQuality(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string StandardValue = "standard"; + private const string HdValue = "hd"; + + /// Requests image generation with standard, balanced characteristics of quality, cost, and speed. + public static ImageGenerationQuality Standard { get; } = new ImageGenerationQuality(StandardValue); + /// Requests image generation with higher quality, higher cost and lower speed relative to standard. + public static ImageGenerationQuality Hd { get; } = new ImageGenerationQuality(HdValue); + /// Determines if two values are the same. + public static bool operator ==(ImageGenerationQuality left, ImageGenerationQuality right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageGenerationQuality left, ImageGenerationQuality right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageGenerationQuality(string value) => new ImageGenerationQuality(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageGenerationQuality other && Equals(other); + /// + public bool Equals(ImageGenerationQuality other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationResponseFormat.cs new file mode 100644 index 000000000000..b4445f444a22 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationResponseFormat.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The format in which the generated images are returned. + internal readonly partial struct ImageGenerationResponseFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageGenerationResponseFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UrlValue = "url"; + private const string Base64Value = "b64_json"; + + /// Image generation response items should provide a URL from which the image may be retrieved. + public static ImageGenerationResponseFormat Url { get; } = new ImageGenerationResponseFormat(UrlValue); + /// Image generation response items should provide image data as a base64-encoded string. + public static ImageGenerationResponseFormat Base64 { get; } = new ImageGenerationResponseFormat(Base64Value); + /// Determines if two values are the same. + public static bool operator ==(ImageGenerationResponseFormat left, ImageGenerationResponseFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageGenerationResponseFormat left, ImageGenerationResponseFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageGenerationResponseFormat(string value) => new ImageGenerationResponseFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageGenerationResponseFormat other && Equals(other); + /// + public bool Equals(ImageGenerationResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationStyle.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationStyle.cs new file mode 100644 index 000000000000..800d3ae8e5bf --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerationStyle.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// An image generation configuration that specifies how the model should incorporate realism and other visual characteristics. + /// Only configurable with dall-e-3 models. + /// + public readonly partial struct ImageGenerationStyle : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageGenerationStyle(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string NaturalValue = "natural"; + private const string VividValue = "vivid"; + + /// Requests image generation in a natural style with less preference for dramatic and hyper-realistic characteristics. + public static ImageGenerationStyle Natural { get; } = new ImageGenerationStyle(NaturalValue); + /// + /// Requests image generation in a vivid style with a higher preference for dramatic and hyper-realistic + /// characteristics. + /// + public static ImageGenerationStyle Vivid { get; } = new ImageGenerationStyle(VividValue); + /// Determines if two values are the same. + public static bool operator ==(ImageGenerationStyle left, ImageGenerationStyle right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageGenerationStyle left, ImageGenerationStyle right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageGenerationStyle(string value) => new ImageGenerationStyle(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageGenerationStyle other && Equals(other); + /// + public bool Equals(ImageGenerationStyle other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.Serialization.cs new file mode 100644 index 000000000000..505fe797d12f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.Serialization.cs @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class ImageGenerations : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerations)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("created"u8); + writer.WriteNumberValue(Created, "U"); + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + ImageGenerations IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ImageGenerations)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeImageGenerations(document.RootElement, options); + } + + internal static ImageGenerations DeserializeImageGenerations(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DateTimeOffset created = default; + IReadOnlyList data = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("created"u8)) + { + created = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("data"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(ImageGenerationData.DeserializeImageGenerationData(item, options)); + } + data = array; + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new ImageGenerations(created, data, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ImageGenerations)} does not support writing '{options.Format}' format."); + } + } + + ImageGenerations IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerations(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ImageGenerations)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static ImageGenerations FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeImageGenerations(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.cs new file mode 100644 index 000000000000..66823f093e60 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageGenerations.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The result of a successful image generation operation. + public partial class ImageGenerations + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + /// The images generated by the operation. + /// is null. + internal ImageGenerations(DateTimeOffset created, IEnumerable data) + { + Argument.AssertNotNull(data, nameof(data)); + + Created = created; + Data = data.ToList(); + } + + /// Initializes a new instance of . + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + /// The images generated by the operation. + /// Keeps track of any properties unknown to the library. + internal ImageGenerations(DateTimeOffset created, IReadOnlyList data, IDictionary serializedAdditionalRawData) + { + Created = created; + Data = data; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal ImageGenerations() + { + } + + /// + /// A timestamp representing when this operation was started. + /// Expressed in seconds since the Unix epoch of 1970-01-01T00:00:00+0000. + /// + public DateTimeOffset Created { get; } + /// The images generated by the operation. + public IReadOnlyList Data { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageSize.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageSize.cs new file mode 100644 index 000000000000..46b72f092ac6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ImageSize.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The desired size of generated images. + public readonly partial struct ImageSize : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ImageSize(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string Size256x256Value = "256x256"; + private const string Size512x512Value = "512x512"; + private const string Size1024x1024Value = "1024x1024"; + private const string Size1792x1024Value = "1792x1024"; + private const string Size1024x1792Value = "1024x1792"; + + /// + /// Very small image size of 256x256 pixels. + /// Only supported with dall-e-2 models. + /// + public static ImageSize Size256x256 { get; } = new ImageSize(Size256x256Value); + /// + /// A smaller image size of 512x512 pixels. + /// Only supported with dall-e-2 models. + /// + public static ImageSize Size512x512 { get; } = new ImageSize(Size512x512Value); + /// + /// A standard, square image size of 1024x1024 pixels. + /// Supported by both dall-e-2 and dall-e-3 models. + /// + public static ImageSize Size1024x1024 { get; } = new ImageSize(Size1024x1024Value); + /// + /// A wider image size of 1024x1792 pixels. + /// Only supported with dall-e-3 models. + /// + public static ImageSize Size1792x1024 { get; } = new ImageSize(Size1792x1024Value); + /// + /// A taller image size of 1792x1024 pixels. + /// Only supported with dall-e-3 models. + /// + public static ImageSize Size1024x1792 { get; } = new ImageSize(Size1024x1792Value); + /// Determines if two values are the same. + public static bool operator ==(ImageSize left, ImageSize right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ImageSize left, ImageSize right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ImageSize(string value) => new ImageSize(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ImageSize other && Equals(other); + /// + public bool Equals(ImageSize other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.Serialization.cs new file mode 100644 index 000000000000..8022f132816a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class InputAudioContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InputAudioContent)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("data"u8); + writer.WriteStringValue(Data); + writer.WritePropertyName("format"u8); + writer.WriteStringValue(Format.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + InputAudioContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(InputAudioContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeInputAudioContent(document.RootElement, options); + } + + internal static InputAudioContent DeserializeInputAudioContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string data = default; + InputAudioFormat format = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("data"u8)) + { + data = property.Value.GetString(); + continue; + } + if (property.NameEquals("format"u8)) + { + format = new InputAudioFormat(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new InputAudioContent(data, format, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(InputAudioContent)} does not support writing '{options.Format}' format."); + } + } + + InputAudioContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeInputAudioContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(InputAudioContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static InputAudioContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeInputAudioContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.cs new file mode 100644 index 000000000000..67643cd8441d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioContent.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A structured chat content item containing audio data. + public partial class InputAudioContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Base64-encoded audio data. + /// The format of the audio data. + /// is null. + public InputAudioContent(string data, InputAudioFormat format) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data; + Format = format; + } + + /// Initializes a new instance of . + /// Base64-encoded audio data. + /// The format of the audio data. + /// Keeps track of any properties unknown to the library. + internal InputAudioContent(string data, InputAudioFormat format, IDictionary serializedAdditionalRawData) + { + Data = data; + Format = format; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal InputAudioContent() + { + } + + /// Base64-encoded audio data. + public string Data { get; } + /// The format of the audio data. + public InputAudioFormat Format { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioFormat.cs new file mode 100644 index 000000000000..cb9fe41552d9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/InputAudioFormat.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Values to describe the format of the input audio data. + public readonly partial struct InputAudioFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public InputAudioFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string WavValue = "wav"; + private const string Mp3Value = "mp3"; + + /// Specifies that the audio data is in the WAV format. + public static InputAudioFormat Wav { get; } = new InputAudioFormat(WavValue); + /// Specifies that the audio data is in the MP3 format. + public static InputAudioFormat Mp3 { get; } = new InputAudioFormat(Mp3Value); + /// Determines if two values are the same. + public static bool operator ==(InputAudioFormat left, InputAudioFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(InputAudioFormat left, InputAudioFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator InputAudioFormat(string value) => new InputAudioFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is InputAudioFormat other && Equals(other); + /// + public bool Equals(InputAudioFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs index a7187a745f1f..21077f384b16 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Argument.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -8,7 +11,7 @@ namespace Azure.AI.OpenAI { - internal static partial class Argument + internal static class Argument { public static void AssertNotNull(T value, string name) { @@ -19,7 +22,7 @@ public static void AssertNotNull(T value, string name) } public static void AssertNotNull(T? value, string name) - where T : struct + where T : struct { if (!value.HasValue) { @@ -73,7 +76,7 @@ public static void AssertNotNullOrWhiteSpace(string value, string name) } public static void AssertNotDefault(ref T value, string name) - where T : struct, IEquatable + where T : struct, IEquatable { if (value.Equals(default)) { @@ -82,7 +85,7 @@ public static void AssertNotDefault(ref T value, string name) } public static void AssertInRange(T value, T minimum, T maximum, string name) - where T : notnull, IComparable + where T : notnull, IComparable { if (minimum.CompareTo(value) > 0) { @@ -103,7 +106,7 @@ public static void AssertEnumDefined(Type enumType, object value, string name) } public static T CheckNotNull(T value, string name) - where T : class + where T : class { AssertNotNull(value, name); return value; diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs index 83076b9abbe1..8bd92c447cd8 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -8,8 +11,7 @@ namespace Azure.AI.OpenAI { - internal partial class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary - where TKey : notnull + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull { private IDictionary _innerDictionary; @@ -39,22 +41,16 @@ public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) } } - /// Gets the IsUndefined. public bool IsUndefined => _innerDictionary == null; - /// Gets the Count. public int Count => IsUndefined ? 0 : EnsureDictionary().Count; - /// Gets the IsReadOnly. public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; - /// Gets the Keys. public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; - /// Gets the Values. public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; - /// Gets or sets the value associated with the specified key. public TValue this[TKey key] { get @@ -71,10 +67,8 @@ public TValue this[TKey key] } } - /// Gets the Keys. IEnumerable IReadOnlyDictionary.Keys => Keys; - /// Gets the Values. IEnumerable IReadOnlyDictionary.Values => Values; public IEnumerator> GetEnumerator() diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs index 62f9ac0d727d..b06e0a43ffe7 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ChangeTrackingList.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -9,7 +12,7 @@ namespace Azure.AI.OpenAI { - internal partial class ChangeTrackingList : IList, IReadOnlyList + internal class ChangeTrackingList : IList, IReadOnlyList { private IList _innerList; @@ -33,16 +36,12 @@ public ChangeTrackingList(IReadOnlyList innerList) } } - /// Gets the IsUndefined. public bool IsUndefined => _innerList == null; - /// Gets the Count. public int Count => IsUndefined ? 0 : EnsureList().Count; - /// Gets the IsReadOnly. public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; - /// Gets or sets the value associated with the specified key. public T this[int index] { get diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientPipelineExtensions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientPipelineExtensions.cs deleted file mode 100644 index e1d028882494..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientPipelineExtensions.cs +++ /dev/null @@ -1,41 +0,0 @@ -// - -#nullable disable - -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Threading.Tasks; - -namespace Azure.AI.OpenAI -{ - internal static partial class ClientPipelineExtensions - { - public static async ValueTask> ProcessHeadAsBoolMessageAsync(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options) - { - PipelineResponse response = await pipeline.ProcessMessageAsync(message, options).ConfigureAwait(false); - switch (response.Status) - { - case >= 200 and < 300: - return ClientResult.FromValue(true, response); - case >= 400 and < 500: - return ClientResult.FromValue(false, response); - default: - return new ErrorResult(response, new ClientResultException(response)); - } - } - - public static ClientResult ProcessHeadAsBoolMessage(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options) - { - PipelineResponse response = pipeline.ProcessMessage(message, options); - switch (response.Status) - { - case >= 200 and < 300: - return ClientResult.FromValue(true, response); - case >= 400 and < 500: - return ClientResult.FromValue(false, response); - default: - return new ErrorResult(response, new ClientResultException(response)); - } - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientUriBuilder.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientUriBuilder.cs deleted file mode 100644 index 5e8571d1e431..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ClientUriBuilder.cs +++ /dev/null @@ -1,118 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Azure.AI.OpenAI -{ - internal partial class ClientUriBuilder - { - private UriBuilder _uriBuilder; - private StringBuilder _pathBuilder; - private StringBuilder _queryBuilder; - - public ClientUriBuilder() - { - } - - private UriBuilder UriBuilder => _uriBuilder ??= new UriBuilder(); - - private StringBuilder PathBuilder => _pathBuilder ??= new StringBuilder(UriBuilder.Path); - - private StringBuilder QueryBuilder => _queryBuilder ??= new StringBuilder(UriBuilder.Query); - - public void Reset(Uri uri) - { - _uriBuilder = new UriBuilder(uri); - _pathBuilder = new StringBuilder(UriBuilder.Path); - _queryBuilder = new StringBuilder(UriBuilder.Query); - } - - public void AppendPath(string value, bool escape) - { - if (escape) - { - value = Uri.EscapeDataString(value); - } - if (PathBuilder.Length > 0 && PathBuilder[PathBuilder.Length - 1] == '/' && value[0] == '/') - { - PathBuilder.Remove(PathBuilder.Length - 1, 1); - } - PathBuilder.Append(value); - UriBuilder.Path = PathBuilder.ToString(); - } - - public void AppendPath(bool value, bool escape = false) => AppendPath(TypeFormatters.ConvertToString(value), escape); - - public void AppendPath(float value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - - public void AppendPath(double value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - - public void AppendPath(int value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - - public void AppendPath(byte[] value, string format, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value, format), escape); - - public void AppendPath(DateTimeOffset value, string format, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value, format), escape); - - public void AppendPath(TimeSpan value, string format, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value, format), escape); - - public void AppendPath(Guid value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - - public void AppendPath(long value, bool escape = true) => AppendPath(TypeFormatters.ConvertToString(value), escape); - - public void AppendPathDelimited(IEnumerable value, string delimiter, string format = null, bool escape = true) - { - delimiter ??= ","; - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - AppendPath(string.Join(delimiter, stringValues), escape); - } - - public void AppendQuery(string name, string value, bool escape) - { - if (QueryBuilder.Length > 0) - { - QueryBuilder.Append('&'); - } - if (escape) - { - value = Uri.EscapeDataString(value); - } - QueryBuilder.Append(name); - QueryBuilder.Append('='); - QueryBuilder.Append(value); - } - - public void AppendQuery(string name, bool value, bool escape = false) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, float value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, DateTimeOffset value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, TimeSpan value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, double value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, decimal value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, int value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, long value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, TimeSpan value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQuery(string name, byte[] value, string format, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value, format), escape); - - public void AppendQuery(string name, Guid value, bool escape = true) => AppendQuery(name, TypeFormatters.ConvertToString(value), escape); - - public void AppendQueryDelimited(string name, IEnumerable value, string delimiter, string format = null, bool escape = true) - { - delimiter ??= ","; - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - AppendQuery(name, string.Join(delimiter, stringValues), escape); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ErrorResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ErrorResult.cs deleted file mode 100644 index 6e36ec8dc1a9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ErrorResult.cs +++ /dev/null @@ -1,24 +0,0 @@ -// - -#nullable disable - -using System.ClientModel; -using System.ClientModel.Primitives; - -namespace Azure.AI.OpenAI -{ - internal partial class ErrorResult : ClientResult - { - private readonly PipelineResponse _response; - private readonly ClientResultException _exception; - - public ErrorResult(PipelineResponse response, ClientResultException exception) : base(default, response) - { - _response = response; - _exception = exception; - } - - /// Gets the Value. - public override T Value => throw _exception; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs index a5ecbaef527d..37078a018a9a 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/ModelSerializationExtensions.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -8,14 +11,15 @@ using System.Diagnostics; using System.Globalization; using System.Text.Json; +using System.Xml; +using Azure.Core; namespace Azure.AI.OpenAI { - internal static partial class ModelSerializationExtensions + internal static class ModelSerializationExtensions { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); - /// - private static readonly BinaryData _sentinelValue = BinaryData.FromBytes("\"__EMPTY__\""u8.ToArray()); public static object GetObject(this JsonElement element) { @@ -41,14 +45,14 @@ public static object GetObject(this JsonElement element) case JsonValueKind.Null: return null; case JsonValueKind.Object: - Dictionary dictionary = new Dictionary(); + var dictionary = new Dictionary(); foreach (var jsonProperty in element.EnumerateObject()) { dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); } return dictionary; case JsonValueKind.Array: - List list = new List(); + var list = new List(); foreach (var item in element.EnumerateArray()) { list.Add(item.GetObject()); @@ -86,7 +90,7 @@ public static char GetChar(this JsonElement element) { if (element.ValueKind == JsonValueKind.String) { - string text = element.GetString(); + var text = element.GetString(); if (text == null || text.Length != 1) { throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); @@ -100,14 +104,14 @@ public static char GetChar(this JsonElement element) } [Conditional("DEBUG")] - public static void ThrowNonNullablePropertyIsNull(this JsonProperty @property) + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) { - throw new JsonException($"A property '{@property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); } public static string GetRequiredString(this JsonElement element) { - string value = element.GetString(); + var value = element.GetString(); if (value == null) { throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); @@ -174,6 +178,9 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, T value, Mode case IJsonModel jsonModel: jsonModel.Write(writer, options ?? WireOptions); break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; case byte[] bytes: writer.WriteBase64StringValue(bytes); break; @@ -250,11 +257,143 @@ public static void WriteObjectValue(this Utf8JsonWriter writer, object value, Mo writer.WriteObjectValue(value, options); } - internal static bool IsSentinelValue(BinaryData value) + internal static class TypeFormatters { - ReadOnlySpan sentinelSpan = _sentinelValue.ToMemory().Span; - ReadOnlySpan valueSpan = value.ToMemory().Span; - return sentinelSpan.SequenceEqual(valueSpan); + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataRequestContent.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataRequestContent.cs new file mode 100644 index 000000000000..68d9091c6708 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/MultipartFormDataRequestContent.cs @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Globalization; +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.OpenAI +{ + internal class MultipartFormDataRequestContent : RequestContent + { + private readonly System.Net.Http.MultipartFormDataContent _multipartContent; + private static readonly Random _random = new Random(); + private static readonly char[] _boundaryValues = "0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".ToCharArray(); + + public MultipartFormDataRequestContent() + { + _multipartContent = new System.Net.Http.MultipartFormDataContent(CreateBoundary()); + } + + public string ContentType + { + get + { + return _multipartContent.Headers.ContentType.ToString(); + } + } + + internal HttpContent HttpContent => _multipartContent; + + private static string CreateBoundary() + { + Span chars = new char[70]; + byte[] random = new byte[70]; + _random.NextBytes(random); + int mask = 255 >> 2; + for (int i = 0; i < 70; i++) + { + chars[i] = _boundaryValues[random[i] & mask]; + } + return chars.ToString(); + } + + public void Add(string content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new StringContent(content), name, filename, contentType); + } + + public void Add(int content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(long content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(float content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(double content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(decimal content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content.ToString("G", CultureInfo.InvariantCulture); + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(bool content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + string value = content ? "true" : "false"; + Add(new StringContent(value), name, filename, contentType); + } + + public void Add(Stream content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new StreamContent(content), name, filename, contentType); + } + + public void Add(byte[] content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new ByteArrayContent(content), name, filename, contentType); + } + + public void Add(BinaryData content, string name, string filename = null, string contentType = null) + { + Argument.AssertNotNull(content, nameof(content)); + Argument.AssertNotNullOrEmpty(name, nameof(name)); + + Add(new ByteArrayContent(content.ToArray()), name, filename, contentType); + } + + private void Add(HttpContent content, string name, string filename, string contentType) + { + if (filename != null) + { + Argument.AssertNotNullOrEmpty(filename, nameof(filename)); + AddFilenameHeader(content, name, filename); + } + if (contentType != null) + { + Argument.AssertNotNullOrEmpty(contentType, nameof(contentType)); + AddContentTypeHeader(content, contentType); + } + _multipartContent.Add(content, name); + } + + public static void AddFilenameHeader(HttpContent content, string name, string filename) + { + ContentDispositionHeaderValue header = new ContentDispositionHeaderValue("form-data") { Name = name, FileName = filename }; + content.Headers.ContentDisposition = header; + } + + public static void AddContentTypeHeader(HttpContent content, string contentType) + { + MediaTypeHeaderValue header = new MediaTypeHeaderValue(contentType); + content.Headers.ContentType = header; + } + + public override bool TryComputeLength(out long length) + { + if (_multipartContent.Headers.ContentLength is long contentLength) + { + length = contentLength; + return true; + } + length = 0; + return false; + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { +#if NET6_0_OR_GREATER + _multipartContent.CopyTo(stream, default, cancellationToken); +#else +#pragma warning disable AZC0107 + _multipartContent.CopyToAsync(stream).EnsureCompleted(); +#pragma warning restore AZC0107 +#endif + } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { +#if NET6_0_OR_GREATER + await _multipartContent.CopyToAsync(stream, cancellationToken).ConfigureAwait(false); +#else + await _multipartContent.CopyToAsync(stream).ConfigureAwait(false); +#endif + } + + public override void Dispose() + { + _multipartContent.Dispose(); + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs index 4ea4dafd04d3..a58dc86ec6a1 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Optional.cs @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable @@ -7,7 +10,7 @@ namespace Azure.AI.OpenAI { - internal static partial class Optional + internal static class Optional { public static bool IsCollectionDefined(IEnumerable collection) { @@ -25,7 +28,7 @@ public static bool IsCollectionDefined(IReadOnlyDictionary(T? value) - where T : struct + where T : struct { return value.HasValue; } @@ -35,14 +38,14 @@ public static bool IsDefined(object value) return value != null; } - public static bool IsDefined(string value) + public static bool IsDefined(JsonElement value) { - return value != null; + return value.ValueKind != JsonValueKind.Undefined; } - public static bool IsDefined(JsonElement value) + public static bool IsDefined(string value) { - return value.ValueKind != JsonValueKind.Undefined; + return value != null; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/PipelineRequestHeadersExtensions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/PipelineRequestHeadersExtensions.cs deleted file mode 100644 index 1fbb4104a79f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/PipelineRequestHeadersExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -// - -#nullable disable - -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Linq; - -namespace Azure.AI.OpenAI -{ - internal static partial class PipelineRequestHeadersExtensions - { - public static void SetDelimited(this PipelineRequestHeaders headers, string name, IEnumerable value, string delimiter) - { - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v)); - headers.Set(name, string.Join(delimiter, stringValues)); - } - - public static void SetDelimited(this PipelineRequestHeaders headers, string name, IEnumerable value, string delimiter, string format) - { - IEnumerable stringValues = value.Select(v => TypeFormatters.ConvertToString(v, format)); - headers.Set(name, string.Join(delimiter, stringValues)); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/TypeFormatters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/TypeFormatters.cs deleted file mode 100644 index c2d0f67ca574..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/TypeFormatters.cs +++ /dev/null @@ -1,150 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Xml; - -namespace Azure.AI.OpenAI -{ - internal static partial class TypeFormatters - { - private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; - public const string DefaultNumberFormat = "G"; - - public static string ToString(bool value) => value ? "true" : "false"; - - public static string ToString(DateTime value, string format) => value.Kind switch - { - DateTimeKind.Utc => ToString((DateTimeOffset)value, format), - _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Generated clients require it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") - }; - - public static string ToString(DateTimeOffset value, string format) => format switch - { - "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), - "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), - "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), - "R" => value.ToString("r", CultureInfo.InvariantCulture), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(TimeSpan value, string format) => format switch - { - "P" => System.Xml.XmlConvert.ToString(value), - _ => value.ToString(format, CultureInfo.InvariantCulture) - }; - - public static string ToString(byte[] value, string format) => format switch - { - "U" => ToBase64UrlString(value), - "D" => Convert.ToBase64String(value), - _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) - }; - - public static string ToBase64UrlString(byte[] value) - { - int numWholeOrPartialInputBlocks = checked (value.Length + 2) / 3; - int size = checked (numWholeOrPartialInputBlocks * 4); - char[] output = new char[size]; - - int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); - - int i = 0; - for (; i < numBase64Chars; i++) - { - char ch = output[i]; - if (ch == '+') - { - output[i] = '-'; - } - else - { - if (ch == '/') - { - output[i] = '_'; - } - else - { - if (ch == '=') - { - break; - } - } - } - } - - return new string(output, 0, i); - } - - public static byte[] FromBase64UrlString(string value) - { - int paddingCharsToAdd = (value.Length % 4) switch - { - 0 => 0, - 2 => 2, - 3 => 1, - _ => throw new InvalidOperationException("Malformed input") - }; - char[] output = new char[(value.Length + paddingCharsToAdd)]; - int i = 0; - for (; i < value.Length; i++) - { - char ch = value[i]; - if (ch == '-') - { - output[i] = '+'; - } - else - { - if (ch == '_') - { - output[i] = '/'; - } - else - { - output[i] = ch; - } - } - } - - for (; i < output.Length; i++) - { - output[i] = '='; - } - - return Convert.FromBase64CharArray(output, 0, output.Length); - } - - public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch - { - "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), - _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) - }; - - public static TimeSpan ParseTimeSpan(string value, string format) => format switch - { - "P" => System.Xml.XmlConvert.ToTimeSpan(value), - _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) - }; - - public static string ConvertToString(object value, string format = null) => value switch - { - null => "null", - string s => s, - bool b => ToString(b), - int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), - byte[] b0 when format != null => ToString(b0, format), - IEnumerable s0 => string.Join(",", s0), - DateTimeOffset dateTime when format != null => ToString(dateTime, format), - TimeSpan timeSpan when format != null => ToString(timeSpan, format), - TimeSpan timeSpan0 => System.Xml.XmlConvert.ToString(timeSpan0), - Guid guid => guid.ToString(), - BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), - _ => value.ToString() - }; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonBinaryContent.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonRequestContent.cs similarity index 82% rename from sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonBinaryContent.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonRequestContent.cs index 9446161ca5c7..62b7404a506e 100644 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonBinaryContent.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -1,28 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + // #nullable disable -using System.ClientModel; using System.IO; using System.Text.Json; using System.Threading; using System.Threading.Tasks; +using Azure.Core; namespace Azure.AI.OpenAI { - internal partial class Utf8JsonBinaryContent : BinaryContent + internal class Utf8JsonRequestContent : RequestContent { private readonly MemoryStream _stream; - private readonly BinaryContent _content; + private readonly RequestContent _content; - public Utf8JsonBinaryContent() + public Utf8JsonRequestContent() { _stream = new MemoryStream(); _content = Create(_stream); JsonWriter = new Utf8JsonWriter(_stream); } - /// Gets the JsonWriter. public Utf8JsonWriter JsonWriter { get; } public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationAnchor.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationAnchor.cs deleted file mode 100644 index c432f67623f6..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationAnchor.cs +++ /dev/null @@ -1,59 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Files -{ - /// - public readonly partial struct AzureFileExpirationAnchor : IEquatable - { - private readonly string _value; - /// Defines the anchor relative to the `created_at` time. - private const string CreatedAtValue = "created_at"; - - /// Initializes a new instance of . - /// The value. - /// is null. - public AzureFileExpirationAnchor(string value) - { - Argument.AssertNotNull(value, nameof(value)); - - _value = value; - } - - /// Defines the anchor relative to the `created_at` time. - public static AzureFileExpirationAnchor CreatedAt { get; } = new AzureFileExpirationAnchor(CreatedAtValue); - - /// Determines if two values are the same. - /// The left value to compare. - /// The right value to compare. - public static bool operator ==(AzureFileExpirationAnchor left, AzureFileExpirationAnchor right) => left.Equals(right); - - /// Determines if two values are not the same. - /// The left value to compare. - /// The right value to compare. - public static bool operator !=(AzureFileExpirationAnchor left, AzureFileExpirationAnchor right) => !left.Equals(right); - - /// Converts a string to a . - /// The value. - public static implicit operator AzureFileExpirationAnchor(string value) => new AzureFileExpirationAnchor(value); - - /// The object to compare. - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is AzureFileExpirationAnchor other && Equals(other); - - /// The instance to compare. - public bool Equals(AzureFileExpirationAnchor other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.Serialization.cs deleted file mode 100644 index 4035ed149991..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.Serialization.cs +++ /dev/null @@ -1,166 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Files -{ - /// - public partial class AzureFileExpirationOptions : IJsonModel - { - internal AzureFileExpirationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureFileExpirationOptions)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("seconds") != true) - { - writer.WritePropertyName("seconds"u8); - writer.WriteNumberValue(Seconds); - } - if (_additionalBinaryDataProperties?.ContainsKey("anchor") != true) - { - writer.WritePropertyName("anchor"u8); - writer.WriteStringValue(Anchor.ToString()); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - AzureFileExpirationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual AzureFileExpirationOptions JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureFileExpirationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureFileExpirationOptions(document.RootElement, options); - } - - internal static AzureFileExpirationOptions DeserializeAzureFileExpirationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int seconds = default; - AzureFileExpirationAnchor anchor = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("seconds"u8)) - { - seconds = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("anchor"u8)) - { - anchor = new AzureFileExpirationAnchor(prop.Value.GetString()); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new AzureFileExpirationOptions(seconds, anchor, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(AzureFileExpirationOptions)} does not support writing '{options.Format}' format."); - } - } - - AzureFileExpirationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual AzureFileExpirationOptions PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeAzureFileExpirationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureFileExpirationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(AzureFileExpirationOptions azureFileExpirationOptions) - { - if (azureFileExpirationOptions == null) - { - return null; - } - return BinaryContent.Create(azureFileExpirationOptions, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator AzureFileExpirationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeAzureFileExpirationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.cs deleted file mode 100644 index 05bcda09f348..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureFileExpirationOptions.cs +++ /dev/null @@ -1,45 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Files -{ - /// The AzureFileExpirationOptions. - public partial class AzureFileExpirationOptions - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - /// Initializes a new instance of . - /// - /// - public AzureFileExpirationOptions(int seconds, AzureFileExpirationAnchor anchor) - { - Seconds = seconds; - Anchor = anchor; - } - - internal AzureFileExpirationOptions(int seconds, AzureFileExpirationAnchor anchor, IDictionary additionalBinaryDataProperties) - { - Seconds = seconds; - Anchor = anchor; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Gets the Seconds. - public int Seconds { get; } - - /// Gets the Anchor. - public AzureFileExpirationAnchor Anchor { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.Serialization.cs deleted file mode 100644 index 8ad0d6ac72a9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.Serialization.cs +++ /dev/null @@ -1,194 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIChatError : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIChatError)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code); - } - if (Optional.IsDefined(Message) && _additionalBinaryDataProperties?.ContainsKey("message") != true) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - if (Optional.IsDefined(Param) && _additionalBinaryDataProperties?.ContainsKey("param") != true) - { - writer.WritePropertyName("param"u8); - writer.WriteStringValue(Param); - } - if (Optional.IsDefined(Type) && _additionalBinaryDataProperties?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (Optional.IsDefined(InnerError) && _additionalBinaryDataProperties?.ContainsKey("inner_error") != true) - { - writer.WritePropertyName("inner_error"u8); - writer.WriteObjectValue(InnerError, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - AzureOpenAIChatError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual AzureOpenAIChatError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIChatError)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIChatError(document.RootElement, options); - } - - internal static AzureOpenAIChatError DeserializeAzureOpenAIChatError(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string code = default; - string message = default; - string @param = default; - string @type = default; - InternalAzureOpenAIChatErrorInnerError innerError = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("code"u8)) - { - code = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("message"u8)) - { - message = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("param"u8)) - { - @param = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("inner_error"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - innerError = InternalAzureOpenAIChatErrorInnerError.DeserializeInternalAzureOpenAIChatErrorInnerError(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new AzureOpenAIChatError( - code, - message, - @param, - @type, - innerError, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(AzureOpenAIChatError)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIChatError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual AzureOpenAIChatError PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeAzureOpenAIChatError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIChatError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(AzureOpenAIChatError azureOpenAIChatError) - { - if (azureOpenAIChatError == null) - { - return null; - } - return BinaryContent.Create(azureOpenAIChatError, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator AzureOpenAIChatError(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIChatError(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.cs deleted file mode 100644 index b0b86dd3e3a0..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatError.cs +++ /dev/null @@ -1,51 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIChatError - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal AzureOpenAIChatError() - { - } - - internal AzureOpenAIChatError(string code, string message, string @param, string @type, InternalAzureOpenAIChatErrorInnerError innerError, IDictionary additionalBinaryDataProperties) - { - Code = code; - Message = message; - Param = @param; - Type = @type; - InnerError = innerError; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The distinct, machine-generated identifier for the error. - public string Code { get; } - - /// A human-readable message associated with the error. - public string Message { get; } - - /// If applicable, the request input parameter associated with the error. - public string Param { get; } - - /// If applicable, the input line number associated with the error. - public string Type { get; } - - /// If applicable, an upstream error that originated this error. - public InternalAzureOpenAIChatErrorInnerError InnerError { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.Serialization.cs deleted file mode 100644 index 47804130d2d9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.Serialization.cs +++ /dev/null @@ -1,144 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIChatErrorResponse : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIChatErrorResponse)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Error) && _additionalBinaryDataProperties?.ContainsKey("error") != true) - { - writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - AzureOpenAIChatErrorResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual AzureOpenAIChatErrorResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIChatErrorResponse)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIChatErrorResponse(document.RootElement, options); - } - - internal static AzureOpenAIChatErrorResponse DeserializeAzureOpenAIChatErrorResponse(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureOpenAIChatError error = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("error"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = AzureOpenAIChatError.DeserializeAzureOpenAIChatError(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new AzureOpenAIChatErrorResponse(error, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(AzureOpenAIChatErrorResponse)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIChatErrorResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual AzureOpenAIChatErrorResponse PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeAzureOpenAIChatErrorResponse(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIChatErrorResponse)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(AzureOpenAIChatErrorResponse azureOpenAIChatErrorResponse) - { - if (azureOpenAIChatErrorResponse == null) - { - return null; - } - return BinaryContent.Create(azureOpenAIChatErrorResponse, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator AzureOpenAIChatErrorResponse(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIChatErrorResponse(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.cs deleted file mode 100644 index c4a1356ff4b5..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIChatErrorResponse.cs +++ /dev/null @@ -1,35 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIChatErrorResponse - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal AzureOpenAIChatErrorResponse() - { - } - - internal AzureOpenAIChatErrorResponse(AzureOpenAIChatError error, IDictionary additionalBinaryDataProperties) - { - Error = error; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Gets the Error. - public AzureOpenAIChatError Error { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.Serialization.cs deleted file mode 100644 index 7eb6d9501340..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.Serialization.cs +++ /dev/null @@ -1,194 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIDalleError : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIDalleError)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code); - } - if (Optional.IsDefined(Message) && _additionalBinaryDataProperties?.ContainsKey("message") != true) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - if (Optional.IsDefined(Param) && _additionalBinaryDataProperties?.ContainsKey("param") != true) - { - writer.WritePropertyName("param"u8); - writer.WriteStringValue(Param); - } - if (Optional.IsDefined(Type) && _additionalBinaryDataProperties?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (Optional.IsDefined(InnerError) && _additionalBinaryDataProperties?.ContainsKey("inner_error") != true) - { - writer.WritePropertyName("inner_error"u8); - writer.WriteObjectValue(InnerError, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - AzureOpenAIDalleError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual AzureOpenAIDalleError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIDalleError)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIDalleError(document.RootElement, options); - } - - internal static AzureOpenAIDalleError DeserializeAzureOpenAIDalleError(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string code = default; - string message = default; - string @param = default; - string @type = default; - InternalAzureOpenAIDalleErrorInnerError innerError = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("code"u8)) - { - code = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("message"u8)) - { - message = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("param"u8)) - { - @param = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("inner_error"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - innerError = InternalAzureOpenAIDalleErrorInnerError.DeserializeInternalAzureOpenAIDalleErrorInnerError(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new AzureOpenAIDalleError( - code, - message, - @param, - @type, - innerError, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(AzureOpenAIDalleError)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIDalleError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual AzureOpenAIDalleError PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeAzureOpenAIDalleError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIDalleError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(AzureOpenAIDalleError azureOpenAIDalleError) - { - if (azureOpenAIDalleError == null) - { - return null; - } - return BinaryContent.Create(azureOpenAIDalleError, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator AzureOpenAIDalleError(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIDalleError(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.cs deleted file mode 100644 index 9a3f1db1f57c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleError.cs +++ /dev/null @@ -1,51 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIDalleError - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal AzureOpenAIDalleError() - { - } - - internal AzureOpenAIDalleError(string code, string message, string @param, string @type, InternalAzureOpenAIDalleErrorInnerError innerError, IDictionary additionalBinaryDataProperties) - { - Code = code; - Message = message; - Param = @param; - Type = @type; - InnerError = innerError; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The distinct, machine-generated identifier for the error. - public string Code { get; } - - /// A human-readable message associated with the error. - public string Message { get; } - - /// If applicable, the request input parameter associated with the error. - public string Param { get; } - - /// If applicable, the input line number associated with the error. - public string Type { get; } - - /// If applicable, an upstream error that originated this error. - public InternalAzureOpenAIDalleErrorInnerError InnerError { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.Serialization.cs deleted file mode 100644 index d82f217b9831..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.Serialization.cs +++ /dev/null @@ -1,144 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIDalleErrorResponse : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIDalleErrorResponse)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Error) && _additionalBinaryDataProperties?.ContainsKey("error") != true) - { - writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - AzureOpenAIDalleErrorResponse IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual AzureOpenAIDalleErrorResponse JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureOpenAIDalleErrorResponse)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureOpenAIDalleErrorResponse(document.RootElement, options); - } - - internal static AzureOpenAIDalleErrorResponse DeserializeAzureOpenAIDalleErrorResponse(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - AzureOpenAIDalleError error = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("error"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = AzureOpenAIDalleError.DeserializeAzureOpenAIDalleError(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new AzureOpenAIDalleErrorResponse(error, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(AzureOpenAIDalleErrorResponse)} does not support writing '{options.Format}' format."); - } - } - - AzureOpenAIDalleErrorResponse IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual AzureOpenAIDalleErrorResponse PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeAzureOpenAIDalleErrorResponse(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureOpenAIDalleErrorResponse)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(AzureOpenAIDalleErrorResponse azureOpenAIDalleErrorResponse) - { - if (azureOpenAIDalleErrorResponse == null) - { - return null; - } - return BinaryContent.Create(azureOpenAIDalleErrorResponse, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator AzureOpenAIDalleErrorResponse(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeAzureOpenAIDalleErrorResponse(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.cs deleted file mode 100644 index d4a90f70a9d7..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureOpenAIDalleErrorResponse.cs +++ /dev/null @@ -1,35 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class AzureOpenAIDalleErrorResponse - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal AzureOpenAIDalleErrorResponse() - { - } - - internal AzureOpenAIDalleErrorResponse(AzureOpenAIDalleError error, IDictionary additionalBinaryDataProperties) - { - Error = error; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Gets the Error. - public AzureOpenAIDalleError Error { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.Serialization.cs deleted file mode 100644 index 0cba4b98bf43..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.Serialization.cs +++ /dev/null @@ -1,139 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class AzureSearchChatDataSource : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureSearchChatDataSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - } - - AzureSearchChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (AzureSearchChatDataSource)JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected override ChatDataSource JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(AzureSearchChatDataSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeAzureSearchChatDataSource(document.RootElement, options); - } - - internal static AzureSearchChatDataSource DeserializeAzureSearchChatDataSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "azure_search"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - InternalAzureSearchChatDataSourceParameters internalParameters = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("parameters"u8)) - { - internalParameters = InternalAzureSearchChatDataSourceParameters.DeserializeInternalAzureSearchChatDataSourceParameters(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new AzureSearchChatDataSource(@type, additionalBinaryDataProperties, internalParameters); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(AzureSearchChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - AzureSearchChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (AzureSearchChatDataSource)PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected override ChatDataSource PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeAzureSearchChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(AzureSearchChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(AzureSearchChatDataSource azureSearchChatDataSource) - { - if (azureSearchChatDataSource == null) - { - return null; - } - return BinaryContent.Create(azureSearchChatDataSource, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator AzureSearchChatDataSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeAzureSearchChatDataSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.cs deleted file mode 100644 index 98028c7fedd9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/AzureSearchChatDataSource.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Azure.AI.OpenAI.Chat -{ - /// Represents a data source configuration that will use an Azure Search resource. - public partial class AzureSearchChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.Serialization.cs deleted file mode 100644 index 739dbc3ce22b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.Serialization.cs +++ /dev/null @@ -1,221 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class ChatCitation : IJsonModel - { - internal ChatCitation() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatCitation)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("content") != true) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content); - } - if (Optional.IsDefined(Title) && _additionalBinaryDataProperties?.ContainsKey("title") != true) - { - writer.WritePropertyName("title"u8); - writer.WriteStringValue(Title); - } - if (Optional.IsDefined(Url) && _additionalBinaryDataProperties?.ContainsKey("url") != true) - { - writer.WritePropertyName("url"u8); - writer.WriteStringValue(Url); - } - if (Optional.IsDefined(ChunkId) && _additionalBinaryDataProperties?.ContainsKey("chunk_id") != true) - { - writer.WritePropertyName("chunk_id"u8); - writer.WriteStringValue(ChunkId); - } - if (Optional.IsDefined(RerankScore) && _additionalBinaryDataProperties?.ContainsKey("rerank_score") != true) - { - writer.WritePropertyName("rerank_score"u8); - writer.WriteNumberValue(RerankScore.Value); - } - if (Optional.IsDefined(FilePath) && _additionalBinaryDataProperties?.ContainsKey("filepath") != true) - { - writer.WritePropertyName("filepath"u8); - writer.WriteStringValue(FilePath); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ChatCitation IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ChatCitation JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatCitation)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatCitation(document.RootElement, options); - } - - internal static ChatCitation DeserializeChatCitation(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string content = default; - string title = default; - string url = default; - string chunkId = default; - double? rerankScore = default; - string filePath = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("content"u8)) - { - content = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("title"u8)) - { - title = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("url"u8)) - { - url = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("chunk_id"u8)) - { - chunkId = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("rerank_score"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - rerankScore = prop.Value.GetDouble(); - continue; - } - if (prop.NameEquals("filepath"u8)) - { - filePath = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ChatCitation( - content, - title, - url, - chunkId, - rerankScore, - filePath, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ChatCitation)} does not support writing '{options.Format}' format."); - } - } - - ChatCitation IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ChatCitation PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeChatCitation(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ChatCitation)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ChatCitation chatCitation) - { - if (chatCitation == null) - { - return null; - } - return BinaryContent.Create(chatCitation, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ChatCitation(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeChatCitation(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.cs deleted file mode 100644 index c573e3dd4e57..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatCitation.cs +++ /dev/null @@ -1,54 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The ChatCitation. - public partial class ChatCitation - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ChatCitation(string content) - { - Content = content; - } - - internal ChatCitation(string content, string title, string url, string chunkId, double? rerankScore, string filePath, IDictionary additionalBinaryDataProperties) - { - Content = content; - Title = title; - Url = url; - ChunkId = chunkId; - RerankScore = rerankScore; - FilePath = filePath; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The content of the citation. - public string Content { get; } - - /// The title for the citation. - public string Title { get; } - - /// The URL of the citation. - public string Url { get; } - - /// The chunk ID for the citation. - public string ChunkId { get; } - - /// The rerank score for the retrieval. - public double? RerankScore { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.Serialization.cs deleted file mode 100644 index 603be85a625c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.Serialization.cs +++ /dev/null @@ -1,157 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - [PersistableModelProxy(typeof(InternalUnknownAzureChatDataSource))] - public abstract partial class ChatDataSource : IJsonModel - { - internal ChatDataSource() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatDataSource)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ChatDataSource JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatDataSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatDataSource(document.RootElement, options); - } - - internal static ChatDataSource DeserializeChatDataSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - if (element.TryGetProperty("type"u8, out JsonElement discriminator)) - { - switch (discriminator.GetString()) - { - case "azure_search": - return AzureSearchChatDataSource.DeserializeAzureSearchChatDataSource(element, options); - case "azure_cosmos_db": - return CosmosChatDataSource.DeserializeCosmosChatDataSource(element, options); - case "elasticsearch": - return ElasticsearchChatDataSource.DeserializeElasticsearchChatDataSource(element, options); - case "pinecone": - return PineconeChatDataSource.DeserializePineconeChatDataSource(element, options); - case "mongo_db": - return MongoDBChatDataSource.DeserializeMongoDBChatDataSource(element, options); - } - } - return InternalUnknownAzureChatDataSource.DeserializeInternalUnknownAzureChatDataSource(element, options); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - ChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ChatDataSource PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ChatDataSource chatDataSource) - { - if (chatDataSource == null) - { - return null; - } - return BinaryContent.Create(chatDataSource, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ChatDataSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeChatDataSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.cs deleted file mode 100644 index f01baf40c0aa..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDataSource.cs +++ /dev/null @@ -1,43 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// - /// A representation of configuration data for a single Azure OpenAI chat data source. - /// 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. - /// Please note this is the abstract base class. The derived classes available for instantiation are: , , , , and . - /// - public abstract partial class ChatDataSource - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - private protected ChatDataSource(string @type) - { - Type = @type; - } - - internal ChatDataSource(string @type, IDictionary additionalBinaryDataProperties) - { - Type = @type; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The differentiating type identifier for the data source. - internal string Type { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDocumentFilterReason.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDocumentFilterReason.cs deleted file mode 100644 index 7702be0f4703..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatDocumentFilterReason.cs +++ /dev/null @@ -1,62 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public readonly partial struct ChatDocumentFilterReason : IEquatable - { - private readonly string _value; - private const string ScoreValue = "score"; - private const string RerankValue = "rerank"; - - /// Initializes a new instance of . - /// The value. - /// is null. - public ChatDocumentFilterReason(string value) - { - Argument.AssertNotNull(value, nameof(value)); - - _value = value; - } - - /// Gets the Score. - public static ChatDocumentFilterReason Score { get; } = new ChatDocumentFilterReason(ScoreValue); - - /// Gets the Rerank. - public static ChatDocumentFilterReason Rerank { get; } = new ChatDocumentFilterReason(RerankValue); - - /// Determines if two values are the same. - /// The left value to compare. - /// The right value to compare. - public static bool operator ==(ChatDocumentFilterReason left, ChatDocumentFilterReason right) => left.Equals(right); - - /// Determines if two values are not the same. - /// The left value to compare. - /// The right value to compare. - public static bool operator !=(ChatDocumentFilterReason left, ChatDocumentFilterReason right) => !left.Equals(right); - - /// Converts a string to a . - /// The value. - public static implicit operator ChatDocumentFilterReason(string value) => new ChatDocumentFilterReason(value); - - /// The object to compare. - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is ChatDocumentFilterReason other && Equals(other); - - /// The instance to compare. - public bool Equals(ChatDocumentFilterReason other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.Serialization.cs deleted file mode 100644 index e932cd5039a1..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.Serialization.cs +++ /dev/null @@ -1,191 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class ChatMessageContext : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatMessageContext)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Intent) && _additionalBinaryDataProperties?.ContainsKey("intent") != true) - { - writer.WritePropertyName("intent"u8); - writer.WriteStringValue(Intent); - } - if (Optional.IsCollectionDefined(Citations) && _additionalBinaryDataProperties?.ContainsKey("citations") != true) - { - writer.WritePropertyName("citations"u8); - writer.WriteStartArray(); - foreach (ChatCitation item in Citations) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(RetrievedDocuments) && _additionalBinaryDataProperties?.ContainsKey("all_retrieved_documents") != true) - { - writer.WritePropertyName("all_retrieved_documents"u8); - writer.WriteObjectValue(RetrievedDocuments, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ChatMessageContext IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ChatMessageContext JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatMessageContext)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatMessageContext(document.RootElement, options); - } - - internal static ChatMessageContext DeserializeChatMessageContext(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string intent = default; - IList citations = default; - ChatRetrievedDocument retrievedDocuments = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("intent"u8)) - { - intent = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("citations"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - array.Add(ChatCitation.DeserializeChatCitation(item, options)); - } - citations = array; - continue; - } - if (prop.NameEquals("all_retrieved_documents"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - retrievedDocuments = ChatRetrievedDocument.DeserializeChatRetrievedDocument(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ChatMessageContext(intent, citations ?? new ChangeTrackingList(), retrievedDocuments, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ChatMessageContext)} does not support writing '{options.Format}' format."); - } - } - - ChatMessageContext IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ChatMessageContext PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeChatMessageContext(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ChatMessageContext)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ChatMessageContext chatMessageContext) - { - if (chatMessageContext == null) - { - return null; - } - return BinaryContent.Create(chatMessageContext, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ChatMessageContext(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeChatMessageContext(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.cs deleted file mode 100644 index 5f7aa7662a87..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatMessageContext.cs +++ /dev/null @@ -1,46 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - /// An additional property, added to chat completion response messages, produced by the Azure OpenAI service when using - /// extension behavior. This includes intent and citation information from the On Your Data feature. - /// - public partial class ChatMessageContext - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ChatMessageContext() - { - Citations = new ChangeTrackingList(); - } - - internal ChatMessageContext(string intent, IList citations, ChatRetrievedDocument retrievedDocuments, IDictionary additionalBinaryDataProperties) - { - Intent = intent; - Citations = citations; - RetrievedDocuments = retrievedDocuments; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The detected intent from the chat history, which is used to carry conversation context between interactions. - public string Intent { get; } - - /// The citations produced by the data retrieval. - public IList Citations { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.Serialization.cs deleted file mode 100644 index 7bfb3fcee94c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.Serialization.cs +++ /dev/null @@ -1,299 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class ChatRetrievedDocument : IJsonModel - { - internal ChatRetrievedDocument() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatRetrievedDocument)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("content") != true) - { - writer.WritePropertyName("content"u8); - writer.WriteStringValue(Content); - } - if (Optional.IsDefined(Title) && _additionalBinaryDataProperties?.ContainsKey("title") != true) - { - writer.WritePropertyName("title"u8); - writer.WriteStringValue(Title); - } - if (Optional.IsDefined(Url) && _additionalBinaryDataProperties?.ContainsKey("url") != true) - { - writer.WritePropertyName("url"u8); - writer.WriteStringValue(Url); - } - if (Optional.IsDefined(ChunkId) && _additionalBinaryDataProperties?.ContainsKey("chunk_id") != true) - { - writer.WritePropertyName("chunk_id"u8); - writer.WriteStringValue(ChunkId); - } - if (Optional.IsDefined(RerankScore) && _additionalBinaryDataProperties?.ContainsKey("rerank_score") != true) - { - writer.WritePropertyName("rerank_score"u8); - writer.WriteNumberValue(RerankScore.Value); - } - if (_additionalBinaryDataProperties?.ContainsKey("search_queries") != true) - { - writer.WritePropertyName("search_queries"u8); - writer.WriteStartArray(); - foreach (string item in SearchQueries) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (_additionalBinaryDataProperties?.ContainsKey("data_source_index") != true) - { - writer.WritePropertyName("data_source_index"u8); - writer.WriteNumberValue(DataSourceIndex); - } - if (Optional.IsDefined(OriginalSearchScore) && _additionalBinaryDataProperties?.ContainsKey("original_search_score") != true) - { - writer.WritePropertyName("original_search_score"u8); - writer.WriteNumberValue(OriginalSearchScore.Value); - } - if (Optional.IsDefined(FilterReason) && _additionalBinaryDataProperties?.ContainsKey("filter_reason") != true) - { - writer.WritePropertyName("filter_reason"u8); - writer.WriteStringValue(FilterReason.Value.ToString()); - } - if (Optional.IsDefined(FilePath) && _additionalBinaryDataProperties?.ContainsKey("filepath") != true) - { - writer.WritePropertyName("filepath"u8); - writer.WriteStringValue(FilePath); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ChatRetrievedDocument IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ChatRetrievedDocument JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatRetrievedDocument)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatRetrievedDocument(document.RootElement, options); - } - - internal static ChatRetrievedDocument DeserializeChatRetrievedDocument(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string content = default; - string title = default; - string url = default; - string chunkId = default; - double? rerankScore = default; - IList searchQueries = default; - int dataSourceIndex = default; - double? originalSearchScore = default; - ChatDocumentFilterReason? filterReason = default; - string filePath = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("content"u8)) - { - content = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("title"u8)) - { - title = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("url"u8)) - { - url = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("chunk_id"u8)) - { - chunkId = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("rerank_score"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - rerankScore = prop.Value.GetDouble(); - continue; - } - if (prop.NameEquals("search_queries"u8)) - { - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - searchQueries = array; - continue; - } - if (prop.NameEquals("data_source_index"u8)) - { - dataSourceIndex = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("original_search_score"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - originalSearchScore = prop.Value.GetDouble(); - continue; - } - if (prop.NameEquals("filter_reason"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - filterReason = new ChatDocumentFilterReason(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("filepath"u8)) - { - filePath = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ChatRetrievedDocument( - content, - title, - url, - chunkId, - rerankScore, - searchQueries, - dataSourceIndex, - originalSearchScore, - filterReason, - filePath, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ChatRetrievedDocument)} does not support writing '{options.Format}' format."); - } - } - - ChatRetrievedDocument IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ChatRetrievedDocument PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeChatRetrievedDocument(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ChatRetrievedDocument)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ChatRetrievedDocument chatRetrievedDocument) - { - if (chatRetrievedDocument == null) - { - return null; - } - return BinaryContent.Create(chatRetrievedDocument, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ChatRetrievedDocument(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeChatRetrievedDocument(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.cs deleted file mode 100644 index 207cf3b6ec9b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ChatRetrievedDocument.cs +++ /dev/null @@ -1,73 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Azure.AI.OpenAI.Chat -{ - /// The ChatRetrievedDocument. - public partial class ChatRetrievedDocument - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ChatRetrievedDocument(string content, IEnumerable searchQueries, int dataSourceIndex) - { - Content = content; - SearchQueries = searchQueries.ToList(); - DataSourceIndex = dataSourceIndex; - } - - internal ChatRetrievedDocument(string content, string title, string url, string chunkId, double? rerankScore, IList searchQueries, int dataSourceIndex, double? originalSearchScore, ChatDocumentFilterReason? filterReason, string filePath, IDictionary additionalBinaryDataProperties) - { - Content = content; - Title = title; - Url = url; - ChunkId = chunkId; - RerankScore = rerankScore; - SearchQueries = searchQueries; - DataSourceIndex = dataSourceIndex; - OriginalSearchScore = originalSearchScore; - FilterReason = filterReason; - FilePath = filePath; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The content of the citation. - public string Content { get; } - - /// The title for the citation. - public string Title { get; } - - /// The URL of the citation. - public string Url { get; } - - /// The chunk ID for the citation. - public string ChunkId { get; } - - /// The rerank score for the retrieval. - public double? RerankScore { get; } - - /// The search queries executed to retrieve documents. - public IList SearchQueries { get; } - - /// The index of the data source used for retrieval. - public int DataSourceIndex { get; } - - /// The original search score for the retrieval. - public double? OriginalSearchScore { get; } - - /// If applicable, an indication of why the document was filtered. - public ChatDocumentFilterReason? FilterReason { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.Serialization.cs deleted file mode 100644 index 8f858a40ce1a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.Serialization.cs +++ /dev/null @@ -1,179 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ContentFilterBlocklistResult : IJsonModel - { - internal ContentFilterBlocklistResult() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterBlocklistResult)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (Optional.IsCollectionDefined(InternalDetails) && _additionalBinaryDataProperties?.ContainsKey("details") != true) - { - writer.WritePropertyName("details"u8); - writer.WriteStartArray(); - foreach (InternalAzureContentFilterBlocklistResultDetail item in InternalDetails) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ContentFilterBlocklistResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ContentFilterBlocklistResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterBlocklistResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterBlocklistResult(document.RootElement, options); - } - - internal static ContentFilterBlocklistResult DeserializeContentFilterBlocklistResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - IReadOnlyList internalDetails = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("filtered"u8)) - { - filtered = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("details"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - array.Add(InternalAzureContentFilterBlocklistResultDetail.DeserializeInternalAzureContentFilterBlocklistResultDetail(item, options)); - } - internalDetails = array; - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ContentFilterBlocklistResult(filtered, internalDetails ?? new ChangeTrackingList(), additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ContentFilterBlocklistResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterBlocklistResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ContentFilterBlocklistResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeContentFilterBlocklistResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterBlocklistResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ContentFilterBlocklistResult contentFilterBlocklistResult) - { - if (contentFilterBlocklistResult == null) - { - return null; - } - return BinaryContent.Create(contentFilterBlocklistResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ContentFilterBlocklistResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterBlocklistResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.cs deleted file mode 100644 index 93cbf6e50c0f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterBlocklistResult.cs +++ /dev/null @@ -1,39 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A collection of true/false filtering results for configured custom blocklists. - public partial class ContentFilterBlocklistResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ContentFilterBlocklistResult(bool filtered) - { - Filtered = filtered; - InternalDetails = new ChangeTrackingList(); - } - - internal ContentFilterBlocklistResult(bool filtered, IReadOnlyList internalDetails, IDictionary additionalBinaryDataProperties) - { - Filtered = filtered; - InternalDetails = internalDetails; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// A value indicating whether any of the detailed blocklists resulted in a filtering action. - public bool Filtered { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.Serialization.cs deleted file mode 100644 index 81ac3f45ff71..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.Serialization.cs +++ /dev/null @@ -1,165 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ContentFilterDetectionResult : IJsonModel - { - internal ContentFilterDetectionResult() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (_additionalBinaryDataProperties?.ContainsKey("detected") != true) - { - writer.WritePropertyName("detected"u8); - writer.WriteBooleanValue(Detected); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ContentFilterDetectionResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ContentFilterDetectionResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterDetectionResult(document.RootElement, options); - } - - internal static ContentFilterDetectionResult DeserializeContentFilterDetectionResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - bool detected = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("filtered"u8)) - { - filtered = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("detected"u8)) - { - detected = prop.Value.GetBoolean(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ContentFilterDetectionResult(filtered, detected, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterDetectionResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ContentFilterDetectionResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeContentFilterDetectionResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterDetectionResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ContentFilterDetectionResult contentFilterDetectionResult) - { - if (contentFilterDetectionResult == null) - { - return null; - } - return BinaryContent.Create(contentFilterDetectionResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ContentFilterDetectionResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterDetectionResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.cs deleted file mode 100644 index 8b52f349fe26..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterDetectionResult.cs +++ /dev/null @@ -1,45 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// - /// A labeled content filter result item that indicates whether the content was detected and whether the content was - /// filtered. - /// - public partial class ContentFilterDetectionResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ContentFilterDetectionResult(bool filtered, bool detected) - { - Filtered = filtered; - Detected = detected; - } - - internal ContentFilterDetectionResult(bool filtered, bool detected, IDictionary additionalBinaryDataProperties) - { - Filtered = filtered; - Detected = detected; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Whether the content detection resulted in a content filtering action. - public bool Filtered { get; } - - /// Whether the labeled content category was detected in the content. - public bool Detected { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.Serialization.cs deleted file mode 100644 index b9c36fc45cd3..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.Serialization.cs +++ /dev/null @@ -1,165 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ContentFilterProtectedMaterialCitationResult : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialCitationResult)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(License) && _additionalBinaryDataProperties?.ContainsKey("license") != true) - { - writer.WritePropertyName("license"u8); - writer.WriteStringValue(License); - } - if (Optional.IsDefined(Uri) && _additionalBinaryDataProperties?.ContainsKey("URL") != true) - { - writer.WritePropertyName("URL"u8); - writer.WriteStringValue(Uri.AbsoluteUri); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ContentFilterProtectedMaterialCitationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ContentFilterProtectedMaterialCitationResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialCitationResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterProtectedMaterialCitationResult(document.RootElement, options); - } - - internal static ContentFilterProtectedMaterialCitationResult DeserializeContentFilterProtectedMaterialCitationResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string license = default; - Uri uri = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("license"u8)) - { - license = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("URL"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - uri = new Uri(prop.Value.GetString()); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ContentFilterProtectedMaterialCitationResult(license, uri, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialCitationResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterProtectedMaterialCitationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ContentFilterProtectedMaterialCitationResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeContentFilterProtectedMaterialCitationResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialCitationResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ContentFilterProtectedMaterialCitationResult contentFilterProtectedMaterialCitationResult) - { - if (contentFilterProtectedMaterialCitationResult == null) - { - return null; - } - return BinaryContent.Create(contentFilterProtectedMaterialCitationResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ContentFilterProtectedMaterialCitationResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterProtectedMaterialCitationResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.cs deleted file mode 100644 index 3177bb7f8bc3..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialCitationResult.cs +++ /dev/null @@ -1,37 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The ContentFilterProtectedMaterialCitationResult. - public partial class ContentFilterProtectedMaterialCitationResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ContentFilterProtectedMaterialCitationResult() - { - } - - internal ContentFilterProtectedMaterialCitationResult(string license, Uri uri, IDictionary additionalBinaryDataProperties) - { - License = license; - Uri = uri; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The name or identifier of the license associated with the detection. - public string License { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.Serialization.cs deleted file mode 100644 index 77ccd8be73c4..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.Serialization.cs +++ /dev/null @@ -1,180 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ContentFilterProtectedMaterialResult : IJsonModel - { - internal ContentFilterProtectedMaterialResult() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialResult)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (_additionalBinaryDataProperties?.ContainsKey("detected") != true) - { - writer.WritePropertyName("detected"u8); - writer.WriteBooleanValue(Detected); - } - if (Optional.IsDefined(Citation) && _additionalBinaryDataProperties?.ContainsKey("citation") != true) - { - writer.WritePropertyName("citation"u8); - writer.WriteObjectValue(Citation, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ContentFilterProtectedMaterialResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ContentFilterProtectedMaterialResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterProtectedMaterialResult(document.RootElement, options); - } - - internal static ContentFilterProtectedMaterialResult DeserializeContentFilterProtectedMaterialResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - bool detected = default; - ContentFilterProtectedMaterialCitationResult citation = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("filtered"u8)) - { - filtered = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("detected"u8)) - { - detected = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("citation"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - citation = ContentFilterProtectedMaterialCitationResult.DeserializeContentFilterProtectedMaterialCitationResult(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ContentFilterProtectedMaterialResult(filtered, detected, citation, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterProtectedMaterialResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ContentFilterProtectedMaterialResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeContentFilterProtectedMaterialResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterProtectedMaterialResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ContentFilterProtectedMaterialResult contentFilterProtectedMaterialResult) - { - if (contentFilterProtectedMaterialResult == null) - { - return null; - } - return BinaryContent.Create(contentFilterProtectedMaterialResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ContentFilterProtectedMaterialResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterProtectedMaterialResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.cs deleted file mode 100644 index ba72e970d66e..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterProtectedMaterialResult.cs +++ /dev/null @@ -1,46 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// The ContentFilterProtectedMaterialResult. - public partial class ContentFilterProtectedMaterialResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ContentFilterProtectedMaterialResult(bool filtered, bool detected) - { - Filtered = filtered; - Detected = detected; - } - - internal ContentFilterProtectedMaterialResult(bool filtered, bool detected, ContentFilterProtectedMaterialCitationResult citation, IDictionary additionalBinaryDataProperties) - { - Filtered = filtered; - Detected = detected; - Citation = citation; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Whether the content detection resulted in a content filtering action. - public bool Filtered { get; } - - /// Whether the labeled content category was detected in the content. - public bool Detected { get; } - - /// If available, the citation details describing the associated license and its location. - public ContentFilterProtectedMaterialCitationResult Citation { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.Serialization.cs deleted file mode 100644 index 39ccf9c5a1e3..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.Serialization.cs +++ /dev/null @@ -1,165 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ContentFilterSeverityResult : IJsonModel - { - internal ContentFilterSeverityResult() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterSeverityResult)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (_additionalBinaryDataProperties?.ContainsKey("severity") != true) - { - writer.WritePropertyName("severity"u8); - writer.WriteStringValue(Severity.ToString()); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ContentFilterSeverityResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ContentFilterSeverityResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterSeverityResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterSeverityResult(document.RootElement, options); - } - - internal static ContentFilterSeverityResult DeserializeContentFilterSeverityResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - ContentFilterSeverity severity = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("filtered"u8)) - { - filtered = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("severity"u8)) - { - severity = new ContentFilterSeverity(prop.Value.GetString()); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ContentFilterSeverityResult(filtered, severity, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ContentFilterSeverityResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterSeverityResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ContentFilterSeverityResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeContentFilterSeverityResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterSeverityResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ContentFilterSeverityResult contentFilterSeverityResult) - { - if (contentFilterSeverityResult == null) - { - return null; - } - return BinaryContent.Create(contentFilterSeverityResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ContentFilterSeverityResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterSeverityResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.cs deleted file mode 100644 index 2bedf2b7076b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterSeverityResult.cs +++ /dev/null @@ -1,42 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// - /// A labeled content filter result item that indicates whether the content was filtered and what the qualitative - /// severity level of the content was, as evaluated against content filter configuration for the category. - /// - public partial class ContentFilterSeverityResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ContentFilterSeverityResult(bool filtered, ContentFilterSeverity severity) - { - Filtered = filtered; - Severity = severity; - } - - internal ContentFilterSeverityResult(bool filtered, ContentFilterSeverity severity, IDictionary additionalBinaryDataProperties) - { - Filtered = filtered; - Severity = severity; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Whether the content severity resulted in a content filtering action. - public bool Filtered { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.Serialization.cs deleted file mode 100644 index 4d8345ec002a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.Serialization.cs +++ /dev/null @@ -1,165 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ContentFilterTextSpan : IJsonModel - { - internal ContentFilterTextSpan() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterTextSpan)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("completion_start_offset") != true) - { - writer.WritePropertyName("completion_start_offset"u8); - writer.WriteNumberValue(CompletionStartOffset); - } - if (_additionalBinaryDataProperties?.ContainsKey("completion_end_offset") != true) - { - writer.WritePropertyName("completion_end_offset"u8); - writer.WriteNumberValue(CompletionEndOffset); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ContentFilterTextSpan IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ContentFilterTextSpan JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterTextSpan)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterTextSpan(document.RootElement, options); - } - - internal static ContentFilterTextSpan DeserializeContentFilterTextSpan(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int completionStartOffset = default; - int completionEndOffset = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("completion_start_offset"u8)) - { - completionStartOffset = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("completion_end_offset"u8)) - { - completionEndOffset = prop.Value.GetInt32(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ContentFilterTextSpan(completionStartOffset, completionEndOffset, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ContentFilterTextSpan)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterTextSpan IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ContentFilterTextSpan PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeContentFilterTextSpan(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterTextSpan)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ContentFilterTextSpan contentFilterTextSpan) - { - if (contentFilterTextSpan == null) - { - return null; - } - return BinaryContent.Create(contentFilterTextSpan, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ContentFilterTextSpan(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterTextSpan(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.cs deleted file mode 100644 index a0f003663a59..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpan.cs +++ /dev/null @@ -1,42 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A representation of a span of completion text as used by Azure OpenAI content filter results. - public partial class ContentFilterTextSpan - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ContentFilterTextSpan(int completionStartOffset, int completionEndOffset) - { - CompletionStartOffset = completionStartOffset; - CompletionEndOffset = completionEndOffset; - } - - internal ContentFilterTextSpan(int completionStartOffset, int completionEndOffset, IDictionary additionalBinaryDataProperties) - { - CompletionStartOffset = completionStartOffset; - CompletionEndOffset = completionEndOffset; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Offset of the UTF32 code point which begins the span. - public int CompletionStartOffset { get; } - - /// Offset of the first UTF32 code point which is excluded from the span. This field is always equal to completion_start_offset for empty spans. This field is always larger than completion_start_offset for non-empty spans. - public int CompletionEndOffset { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.Serialization.cs deleted file mode 100644 index bdf88d163e97..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.Serialization.cs +++ /dev/null @@ -1,186 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ContentFilterTextSpanResult : IJsonModel - { - internal ContentFilterTextSpanResult() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterTextSpanResult)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (_additionalBinaryDataProperties?.ContainsKey("detected") != true) - { - writer.WritePropertyName("detected"u8); - writer.WriteBooleanValue(Detected); - } - if (_additionalBinaryDataProperties?.ContainsKey("details") != true) - { - writer.WritePropertyName("details"u8); - writer.WriteStartArray(); - foreach (ContentFilterTextSpan item in Details) - { - writer.WriteObjectValue(item, options); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ContentFilterTextSpanResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ContentFilterTextSpanResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ContentFilterTextSpanResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeContentFilterTextSpanResult(document.RootElement, options); - } - - internal static ContentFilterTextSpanResult DeserializeContentFilterTextSpanResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - bool detected = default; - IList details = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("filtered"u8)) - { - filtered = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("detected"u8)) - { - detected = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("details"u8)) - { - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - array.Add(ContentFilterTextSpan.DeserializeContentFilterTextSpan(item, options)); - } - details = array; - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ContentFilterTextSpanResult(filtered, detected, details, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ContentFilterTextSpanResult)} does not support writing '{options.Format}' format."); - } - } - - ContentFilterTextSpanResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ContentFilterTextSpanResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeContentFilterTextSpanResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ContentFilterTextSpanResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ContentFilterTextSpanResult contentFilterTextSpanResult) - { - if (contentFilterTextSpanResult == null) - { - return null; - } - return BinaryContent.Create(contentFilterTextSpanResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ContentFilterTextSpanResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeContentFilterTextSpanResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.cs deleted file mode 100644 index 8f4855998b9f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ContentFilterTextSpanResult.cs +++ /dev/null @@ -1,48 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Azure.AI.OpenAI -{ - /// The ContentFilterTextSpanResult. - public partial class ContentFilterTextSpanResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ContentFilterTextSpanResult(bool filtered, bool detected, IEnumerable details) - { - Filtered = filtered; - Detected = detected; - Details = details.ToList(); - } - - internal ContentFilterTextSpanResult(bool filtered, bool detected, IList details, IDictionary additionalBinaryDataProperties) - { - Filtered = filtered; - Detected = detected; - Details = details; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Whether the content detection resulted in a content filtering action. - public bool Filtered { get; } - - /// Whether the labeled content category was detected in the content. - public bool Detected { get; } - - /// Detailed information about the detected completion text spans. - public IList Details { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.Serialization.cs deleted file mode 100644 index 16ae253e1445..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.Serialization.cs +++ /dev/null @@ -1,139 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class CosmosChatDataSource : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CosmosChatDataSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - } - - CosmosChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (CosmosChatDataSource)JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected override ChatDataSource JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(CosmosChatDataSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCosmosChatDataSource(document.RootElement, options); - } - - internal static CosmosChatDataSource DeserializeCosmosChatDataSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "azure_cosmos_db"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - InternalAzureCosmosDBChatDataSourceParameters internalParameters = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("parameters"u8)) - { - internalParameters = InternalAzureCosmosDBChatDataSourceParameters.DeserializeInternalAzureCosmosDBChatDataSourceParameters(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new CosmosChatDataSource(@type, additionalBinaryDataProperties, internalParameters); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(CosmosChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - CosmosChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (CosmosChatDataSource)PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected override ChatDataSource PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeCosmosChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(CosmosChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(CosmosChatDataSource cosmosChatDataSource) - { - if (cosmosChatDataSource == null) - { - return null; - } - return BinaryContent.Create(cosmosChatDataSource, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator CosmosChatDataSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeCosmosChatDataSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.cs deleted file mode 100644 index 58f84cf9ec5a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/CosmosChatDataSource.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Azure.AI.OpenAI.Chat -{ - /// Represents a data source configuration that will use an Azure CosmosDB resource. - public partial class CosmosChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.Serialization.cs deleted file mode 100644 index 6dd771f17530..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.Serialization.cs +++ /dev/null @@ -1,163 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - [PersistableModelProxy(typeof(InternalUnknownAzureChatDataSourceAuthenticationOptions))] - public abstract partial class DataSourceAuthentication : IJsonModel - { - internal DataSourceAuthentication() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DataSourceAuthentication IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceAuthentication(document.RootElement, options); - } - - internal static DataSourceAuthentication DeserializeDataSourceAuthentication(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - if (element.TryGetProperty("type"u8, out JsonElement discriminator)) - { - switch (discriminator.GetString()) - { - case "api_key": - return InternalAzureChatDataSourceApiKeyAuthenticationOptions.DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(element, options); - case "username_and_password": - return InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(element, options); - case "connection_string": - return InternalAzureChatDataSourceConnectionStringAuthenticationOptions.DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(element, options); - case "key_and_key_id": - return InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(element, options); - case "encoded_api_key": - return InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(element, options); - case "access_token": - return InternalAzureChatDataSourceAccessTokenAuthenticationOptions.DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(element, options); - case "system_assigned_managed_identity": - return InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(element, options); - case "user_assigned_managed_identity": - return InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(element, options); - } - } - return InternalUnknownAzureChatDataSourceAuthenticationOptions.DeserializeInternalUnknownAzureChatDataSourceAuthenticationOptions(element, options); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support writing '{options.Format}' format."); - } - } - - DataSourceAuthentication IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeDataSourceAuthentication(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(DataSourceAuthentication dataSourceAuthentication) - { - if (dataSourceAuthentication == null) - { - return null; - } - return BinaryContent.Create(dataSourceAuthentication, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator DataSourceAuthentication(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeDataSourceAuthentication(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.cs deleted file mode 100644 index c5a4f29608b6..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceAuthentication.cs +++ /dev/null @@ -1,40 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// - /// The DataSourceAuthentication. - /// Please note this is the abstract base class. The derived classes available for instantiation are: - /// - public abstract partial class DataSourceAuthentication - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - private protected DataSourceAuthentication(string @type) - { - Type = @type; - } - - internal DataSourceAuthentication(string @type, IDictionary additionalBinaryDataProperties) - { - Type = @type; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// Gets or sets the Type. - internal string Type { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.Serialization.cs deleted file mode 100644 index 74cd1284bfa0..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.Serialization.cs +++ /dev/null @@ -1,303 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class DataSourceFieldMappings : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceFieldMappings)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(TitleFieldName) && _additionalBinaryDataProperties?.ContainsKey("title_field") != true) - { - writer.WritePropertyName("title_field"u8); - writer.WriteStringValue(TitleFieldName); - } - if (Optional.IsDefined(UrlFieldName) && _additionalBinaryDataProperties?.ContainsKey("url_field") != true) - { - writer.WritePropertyName("url_field"u8); - writer.WriteStringValue(UrlFieldName); - } - if (Optional.IsDefined(FilePathFieldName) && _additionalBinaryDataProperties?.ContainsKey("filepath_field") != true) - { - writer.WritePropertyName("filepath_field"u8); - writer.WriteStringValue(FilePathFieldName); - } - if (Optional.IsCollectionDefined(ContentFieldNames) && _additionalBinaryDataProperties?.ContainsKey("content_fields") != true) - { - writer.WritePropertyName("content_fields"u8); - writer.WriteStartArray(); - foreach (string item in ContentFieldNames) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsDefined(ContentFieldSeparator) && _additionalBinaryDataProperties?.ContainsKey("content_fields_separator") != true) - { - writer.WritePropertyName("content_fields_separator"u8); - writer.WriteStringValue(ContentFieldSeparator); - } - if (Optional.IsCollectionDefined(VectorFieldNames) && _additionalBinaryDataProperties?.ContainsKey("vector_fields") != true) - { - writer.WritePropertyName("vector_fields"u8); - writer.WriteStartArray(); - foreach (string item in VectorFieldNames) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (Optional.IsCollectionDefined(ImageVectorFieldNames) && _additionalBinaryDataProperties?.ContainsKey("image_vector_fields") != true) - { - writer.WritePropertyName("image_vector_fields"u8); - writer.WriteStartArray(); - foreach (string item in ImageVectorFieldNames) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DataSourceFieldMappings IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual DataSourceFieldMappings JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceFieldMappings)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceFieldMappings(document.RootElement, options); - } - - internal static DataSourceFieldMappings DeserializeDataSourceFieldMappings(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string titleFieldName = default; - string urlFieldName = default; - string filePathFieldName = default; - IList contentFieldNames = default; - string contentFieldSeparator = default; - IList vectorFieldNames = default; - IList imageVectorFieldNames = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("title_field"u8)) - { - titleFieldName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("url_field"u8)) - { - urlFieldName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("filepath_field"u8)) - { - filePathFieldName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("content_fields"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - contentFieldNames = array; - continue; - } - if (prop.NameEquals("content_fields_separator"u8)) - { - contentFieldSeparator = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("vector_fields"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - vectorFieldNames = array; - continue; - } - if (prop.NameEquals("image_vector_fields"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - imageVectorFieldNames = array; - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new DataSourceFieldMappings( - titleFieldName, - urlFieldName, - filePathFieldName, - contentFieldNames ?? new ChangeTrackingList(), - contentFieldSeparator, - vectorFieldNames ?? new ChangeTrackingList(), - imageVectorFieldNames ?? new ChangeTrackingList(), - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(DataSourceFieldMappings)} does not support writing '{options.Format}' format."); - } - } - - DataSourceFieldMappings IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual DataSourceFieldMappings PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeDataSourceFieldMappings(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceFieldMappings)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(DataSourceFieldMappings dataSourceFieldMappings) - { - if (dataSourceFieldMappings == null) - { - return null; - } - return BinaryContent.Create(dataSourceFieldMappings, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator DataSourceFieldMappings(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeDataSourceFieldMappings(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.cs deleted file mode 100644 index a707d025a037..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceFieldMappings.cs +++ /dev/null @@ -1,35 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// The DataSourceFieldMappings. - public partial class DataSourceFieldMappings - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal DataSourceFieldMappings(string titleFieldName, string urlFieldName, string filePathFieldName, IList contentFieldNames, string contentFieldSeparator, IList vectorFieldNames, IList imageVectorFieldNames, IDictionary additionalBinaryDataProperties) - { - TitleFieldName = titleFieldName; - UrlFieldName = urlFieldName; - FilePathFieldName = filePathFieldName; - ContentFieldNames = contentFieldNames; - ContentFieldSeparator = contentFieldSeparator; - VectorFieldNames = vectorFieldNames; - ImageVectorFieldNames = imageVectorFieldNames; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceQueryType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceQueryType.cs deleted file mode 100644 index f21996d9a759..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceQueryType.cs +++ /dev/null @@ -1,74 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public readonly partial struct DataSourceQueryType : IEquatable - { - private readonly string _value; - private const string SimpleValue = "simple"; - private const string SemanticValue = "semantic"; - private const string VectorValue = "vector"; - private const string VectorSimpleHybridValue = "vector_simple_hybrid"; - private const string VectorSemanticHybridValue = "vector_semantic_hybrid"; - - /// Initializes a new instance of . - /// The value. - /// is null. - public DataSourceQueryType(string value) - { - Argument.AssertNotNull(value, nameof(value)); - - _value = value; - } - - /// Gets the Simple. - public static DataSourceQueryType Simple { get; } = new DataSourceQueryType(SimpleValue); - - /// Gets the Semantic. - public static DataSourceQueryType Semantic { get; } = new DataSourceQueryType(SemanticValue); - - /// Gets the Vector. - public static DataSourceQueryType Vector { get; } = new DataSourceQueryType(VectorValue); - - /// Gets the VectorSimpleHybrid. - public static DataSourceQueryType VectorSimpleHybrid { get; } = new DataSourceQueryType(VectorSimpleHybridValue); - - /// Gets the VectorSemanticHybrid. - public static DataSourceQueryType VectorSemanticHybrid { get; } = new DataSourceQueryType(VectorSemanticHybridValue); - - /// Determines if two values are the same. - /// The left value to compare. - /// The right value to compare. - public static bool operator ==(DataSourceQueryType left, DataSourceQueryType right) => left.Equals(right); - - /// Determines if two values are not the same. - /// The left value to compare. - /// The right value to compare. - public static bool operator !=(DataSourceQueryType left, DataSourceQueryType right) => !left.Equals(right); - - /// Converts a string to a . - /// The value. - public static implicit operator DataSourceQueryType(string value) => new DataSourceQueryType(value); - - /// The object to compare. - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is DataSourceQueryType other && Equals(other); - - /// The instance to compare. - public bool Equals(DataSourceQueryType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.Serialization.cs deleted file mode 100644 index 40cb27bd42be..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.Serialization.cs +++ /dev/null @@ -1,155 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - [PersistableModelProxy(typeof(InternalUnknownAzureChatDataSourceVectorizationSource))] - public abstract partial class DataSourceVectorizer : IJsonModel - { - internal DataSourceVectorizer() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("type") != true) - { - writer.WritePropertyName("type"u8); - writer.WriteStringValue(Type); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - DataSourceVectorizer IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual DataSourceVectorizer JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceVectorizer(document.RootElement, options); - } - - internal static DataSourceVectorizer DeserializeDataSourceVectorizer(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - if (element.TryGetProperty("type"u8, out JsonElement discriminator)) - { - switch (discriminator.GetString()) - { - case "endpoint": - return InternalAzureChatDataSourceEndpointVectorizationSource.DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(element, options); - case "deployment_name": - return InternalAzureChatDataSourceDeploymentNameVectorizationSource.DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(element, options); - case "model_id": - return InternalAzureChatDataSourceModelIdVectorizationSource.DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(element, options); - case "integrated": - return InternalAzureChatDataSourceIntegratedVectorizationSource.DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(element, options); - } - } - return InternalUnknownAzureChatDataSourceVectorizationSource.DeserializeInternalUnknownAzureChatDataSourceVectorizationSource(element, options); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support writing '{options.Format}' format."); - } - } - - DataSourceVectorizer IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual DataSourceVectorizer PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeDataSourceVectorizer(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(DataSourceVectorizer dataSourceVectorizer) - { - if (dataSourceVectorizer == null) - { - return null; - } - return BinaryContent.Create(dataSourceVectorizer, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator DataSourceVectorizer(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeDataSourceVectorizer(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.cs deleted file mode 100644 index 6b492d2477c7..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/DataSourceVectorizer.cs +++ /dev/null @@ -1,40 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - /// - /// A representation of a data vectorization source usable as an embedding resource with a data source. - /// Please note this is the abstract base class. The derived classes available for instantiation are: - /// - public abstract partial class DataSourceVectorizer - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - private protected DataSourceVectorizer(string @type) - { - Type = @type; - } - - internal DataSourceVectorizer(string @type, IDictionary additionalBinaryDataProperties) - { - Type = @type; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The differentiating identifier for the concrete vectorization source. - internal string Type { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.Serialization.cs deleted file mode 100644 index b0275216c4e0..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.Serialization.cs +++ /dev/null @@ -1,139 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class ElasticsearchChatDataSource : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ElasticsearchChatDataSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - } - - ElasticsearchChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (ElasticsearchChatDataSource)JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected override ChatDataSource JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ElasticsearchChatDataSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeElasticsearchChatDataSource(document.RootElement, options); - } - - internal static ElasticsearchChatDataSource DeserializeElasticsearchChatDataSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "elasticsearch"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - InternalElasticsearchChatDataSourceParameters internalParameters = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("parameters"u8)) - { - internalParameters = InternalElasticsearchChatDataSourceParameters.DeserializeInternalElasticsearchChatDataSourceParameters(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ElasticsearchChatDataSource(@type, additionalBinaryDataProperties, internalParameters); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ElasticsearchChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - ElasticsearchChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (ElasticsearchChatDataSource)PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected override ChatDataSource PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeElasticsearchChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ElasticsearchChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ElasticsearchChatDataSource elasticsearchChatDataSource) - { - if (elasticsearchChatDataSource == null) - { - return null; - } - return BinaryContent.Create(elasticsearchChatDataSource, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ElasticsearchChatDataSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeElasticsearchChatDataSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.cs deleted file mode 100644 index aa55edff65c4..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSource.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Azure.AI.OpenAI.Chat -{ - /// The ElasticsearchChatDataSource. - public partial class ElasticsearchChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.Serialization.cs deleted file mode 100644 index 127988706bfa..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.Serialization.cs +++ /dev/null @@ -1,31 +0,0 @@ -// - -#nullable disable - -using System; - -namespace Azure.AI.OpenAI -{ - internal static partial class ElasticsearchChatDataSourceParametersQueryTypeExtensions - { - public static string ToSerialString(this ElasticsearchChatDataSourceParametersQueryType value) => value switch - { - ElasticsearchChatDataSourceParametersQueryType.Simple => "simple", - ElasticsearchChatDataSourceParametersQueryType.Vector => "vector", - _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ElasticsearchChatDataSourceParametersQueryType value.") - }; - - public static ElasticsearchChatDataSourceParametersQueryType ToElasticsearchChatDataSourceParametersQueryType(this string value) - { - if (StringComparer.OrdinalIgnoreCase.Equals(value, "simple")) - { - return ElasticsearchChatDataSourceParametersQueryType.Simple; - } - if (StringComparer.OrdinalIgnoreCase.Equals(value, "vector")) - { - return ElasticsearchChatDataSourceParametersQueryType.Vector; - } - throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown ElasticsearchChatDataSourceParametersQueryType value."); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.cs deleted file mode 100644 index 00a15182d73c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ElasticsearchChatDataSourceParametersQueryType.cs +++ /dev/null @@ -1,15 +0,0 @@ -// - -#nullable disable - -namespace Azure.AI.OpenAI -{ - /// - public enum ElasticsearchChatDataSourceParametersQueryType - { - /// Simple. - Simple, - /// Vector. - Vector - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.Serialization.cs deleted file mode 100644 index 60d260159b2f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceAccessTokenAuthenticationOptions : IJsonModel - { - internal InternalAzureChatDataSourceAccessTokenAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("access_token") != true) - { - writer.WritePropertyName("access_token"u8); - writer.WriteStringValue(AccessToken); - } - } - - InternalAzureChatDataSourceAccessTokenAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceAccessTokenAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceAccessTokenAuthenticationOptions DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "access_token"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string accessToken = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("access_token"u8)) - { - accessToken = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceAccessTokenAuthenticationOptions(@type, additionalBinaryDataProperties, accessToken); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceAccessTokenAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceAccessTokenAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceAccessTokenAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceAccessTokenAuthenticationOptions internalAzureChatDataSourceAccessTokenAuthenticationOptions) - { - if (internalAzureChatDataSourceAccessTokenAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceAccessTokenAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceAccessTokenAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceAccessTokenAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.cs deleted file mode 100644 index ecbf06da5adb..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceAccessTokenAuthenticationOptions.cs +++ /dev/null @@ -1,28 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceAccessTokenAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceAccessTokenAuthenticationOptions(string accessToken) : base("access_token") - { - Argument.AssertNotNull(accessToken, nameof(accessToken)); - - AccessToken = accessToken; - } - - internal InternalAzureChatDataSourceAccessTokenAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties, string accessToken) : base(@type, additionalBinaryDataProperties) - { - AccessToken = accessToken; - } - - /// Gets the AccessToken. - public string AccessToken { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.Serialization.cs deleted file mode 100644 index 7b25e63c2c59..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceApiKeyAuthenticationOptions : IJsonModel - { - internal InternalAzureChatDataSourceApiKeyAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("key") != true) - { - writer.WritePropertyName("key"u8); - writer.WriteStringValue(Key); - } - } - - InternalAzureChatDataSourceApiKeyAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceApiKeyAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceApiKeyAuthenticationOptions DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "api_key"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string key = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("key"u8)) - { - key = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceApiKeyAuthenticationOptions(@type, additionalBinaryDataProperties, key); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceApiKeyAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceApiKeyAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceApiKeyAuthenticationOptions internalAzureChatDataSourceApiKeyAuthenticationOptions) - { - if (internalAzureChatDataSourceApiKeyAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceApiKeyAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceApiKeyAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceApiKeyAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.cs deleted file mode 100644 index 8a069f7db4e2..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceApiKeyAuthenticationOptions.cs +++ /dev/null @@ -1,28 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceApiKeyAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceApiKeyAuthenticationOptions(string key) : base("api_key") - { - Argument.AssertNotNull(key, nameof(key)); - - Key = key; - } - - internal InternalAzureChatDataSourceApiKeyAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties, string key) : base(@type, additionalBinaryDataProperties) - { - Key = key; - } - - /// Gets the Key. - public string Key { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.Serialization.cs deleted file mode 100644 index 68b5fe909a11..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceConnectionStringAuthenticationOptions : IJsonModel - { - internal InternalAzureChatDataSourceConnectionStringAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("connection_string") != true) - { - writer.WritePropertyName("connection_string"u8); - writer.WriteStringValue(ConnectionString); - } - } - - InternalAzureChatDataSourceConnectionStringAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceConnectionStringAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceConnectionStringAuthenticationOptions DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "connection_string"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string connectionString = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("connection_string"u8)) - { - connectionString = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceConnectionStringAuthenticationOptions(@type, additionalBinaryDataProperties, connectionString); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceConnectionStringAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceConnectionStringAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceConnectionStringAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceConnectionStringAuthenticationOptions internalAzureChatDataSourceConnectionStringAuthenticationOptions) - { - if (internalAzureChatDataSourceConnectionStringAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceConnectionStringAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceConnectionStringAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceConnectionStringAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.cs deleted file mode 100644 index d955b475fbb5..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceConnectionStringAuthenticationOptions.cs +++ /dev/null @@ -1,28 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceConnectionStringAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceConnectionStringAuthenticationOptions(string connectionString) : base("connection_string") - { - Argument.AssertNotNull(connectionString, nameof(connectionString)); - - ConnectionString = connectionString; - } - - internal InternalAzureChatDataSourceConnectionStringAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties, string connectionString) : base(@type, additionalBinaryDataProperties) - { - ConnectionString = connectionString; - } - - /// Gets the ConnectionString. - public string ConnectionString { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.Serialization.cs deleted file mode 100644 index f23f38e47c5b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.Serialization.cs +++ /dev/null @@ -1,148 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceDeploymentNameVectorizationSource : IJsonModel - { - internal InternalAzureChatDataSourceDeploymentNameVectorizationSource() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("deployment_name") != true) - { - writer.WritePropertyName("deployment_name"u8); - writer.WriteStringValue(DeploymentName); - } - if (Optional.IsDefined(Dimensions) && _additionalBinaryDataProperties?.ContainsKey("dimensions") != true) - { - writer.WritePropertyName("dimensions"u8); - writer.WriteNumberValue(Dimensions.Value); - } - } - - InternalAzureChatDataSourceDeploymentNameVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceDeploymentNameVectorizationSource)JsonModelCreateCore(ref reader, options); - - protected override DataSourceVectorizer JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceDeploymentNameVectorizationSource DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "deployment_name"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string deploymentName = default; - int? dimensions = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("deployment_name"u8)) - { - deploymentName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("dimensions"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - dimensions = prop.Value.GetInt32(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceDeploymentNameVectorizationSource(@type, additionalBinaryDataProperties, deploymentName, dimensions); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceDeploymentNameVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceDeploymentNameVectorizationSource)PersistableModelCreateCore(data, options); - - protected override DataSourceVectorizer PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceDeploymentNameVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceDeploymentNameVectorizationSource internalAzureChatDataSourceDeploymentNameVectorizationSource) - { - if (internalAzureChatDataSourceDeploymentNameVectorizationSource == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceDeploymentNameVectorizationSource, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceDeploymentNameVectorizationSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceDeploymentNameVectorizationSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.cs deleted file mode 100644 index 17209233ad6b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceDeploymentNameVectorizationSource.cs +++ /dev/null @@ -1,38 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceDeploymentNameVectorizationSource : DataSourceVectorizer - { - public InternalAzureChatDataSourceDeploymentNameVectorizationSource(string deploymentName) : base("deployment_name") - { - Argument.AssertNotNull(deploymentName, nameof(deploymentName)); - - DeploymentName = deploymentName; - } - - internal InternalAzureChatDataSourceDeploymentNameVectorizationSource(string @type, IDictionary additionalBinaryDataProperties, string deploymentName, int? dimensions) : base(@type, additionalBinaryDataProperties) - { - DeploymentName = deploymentName; - Dimensions = dimensions; - } - - /// - /// The embedding model deployment to use for vectorization. This deployment must exist within the same Azure OpenAI - /// resource as the model deployment being used for chat completions. - /// - public string DeploymentName { get; set; } - - /// - /// The number of dimensions to request on embeddings. - /// Only supported in 'text-embedding-3' and later models. - /// - public int? Dimensions { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.Serialization.cs deleted file mode 100644 index a51f8c9f9816..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions : IJsonModel - { - internal InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("encoded_api_key") != true) - { - writer.WritePropertyName("encoded_api_key"u8); - writer.WriteStringValue(EncodedApiKey); - } - } - - InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "encoded_api_key"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string encodedApiKey = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("encoded_api_key"u8)) - { - encodedApiKey = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(@type, additionalBinaryDataProperties, encodedApiKey); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions internalAzureChatDataSourceEncodedApiKeyAuthenticationOptions) - { - if (internalAzureChatDataSourceEncodedApiKeyAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceEncodedApiKeyAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.cs deleted file mode 100644 index ce7b8ec271d6..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions.cs +++ /dev/null @@ -1,28 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(string encodedApiKey) : base("encoded_api_key") - { - Argument.AssertNotNull(encodedApiKey, nameof(encodedApiKey)); - - EncodedApiKey = encodedApiKey; - } - - internal InternalAzureChatDataSourceEncodedApiKeyAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties, string encodedApiKey) : base(@type, additionalBinaryDataProperties) - { - EncodedApiKey = encodedApiKey; - } - - /// Gets the EncodedApiKey. - public string EncodedApiKey { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.Serialization.cs deleted file mode 100644 index dc6a03bd5f76..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.Serialization.cs +++ /dev/null @@ -1,159 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceEndpointVectorizationSource : IJsonModel - { - internal InternalAzureChatDataSourceEndpointVectorizationSource() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint.AbsoluteUri); - } - if (Optional.IsDefined(Dimensions) && _additionalBinaryDataProperties?.ContainsKey("dimensions") != true) - { - writer.WritePropertyName("dimensions"u8); - writer.WriteNumberValue(Dimensions.Value); - } - if (_additionalBinaryDataProperties?.ContainsKey("authentication") != true) - { - writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - } - - InternalAzureChatDataSourceEndpointVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceEndpointVectorizationSource)JsonModelCreateCore(ref reader, options); - - protected override DataSourceVectorizer JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceEndpointVectorizationSource DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "endpoint"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - Uri endpoint = default; - int? dimensions = default; - DataSourceAuthentication authentication = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("endpoint"u8)) - { - endpoint = new Uri(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("dimensions"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - dimensions = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceEndpointVectorizationSource(@type, additionalBinaryDataProperties, endpoint, dimensions, authentication); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceEndpointVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceEndpointVectorizationSource)PersistableModelCreateCore(data, options); - - protected override DataSourceVectorizer PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceEndpointVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceEndpointVectorizationSource internalAzureChatDataSourceEndpointVectorizationSource) - { - if (internalAzureChatDataSourceEndpointVectorizationSource == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceEndpointVectorizationSource, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceEndpointVectorizationSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceEndpointVectorizationSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.cs deleted file mode 100644 index 698392ab5983..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceEndpointVectorizationSource.cs +++ /dev/null @@ -1,43 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceEndpointVectorizationSource : DataSourceVectorizer - { - public InternalAzureChatDataSourceEndpointVectorizationSource(Uri endpoint, DataSourceAuthentication authentication) : base("endpoint") - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(authentication, nameof(authentication)); - - Endpoint = endpoint; - Authentication = authentication; - } - - internal InternalAzureChatDataSourceEndpointVectorizationSource(string @type, IDictionary additionalBinaryDataProperties, Uri endpoint, int? dimensions, DataSourceAuthentication authentication) : base(@type, additionalBinaryDataProperties) - { - Endpoint = endpoint; - Dimensions = dimensions; - Authentication = authentication; - } - - /// - /// 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. - /// - public Uri Endpoint { get; set; } - - /// - /// The number of dimensions to request on embeddings. - /// Only supported in 'text-embedding-3' and later models. - /// - public int? Dimensions { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.Serialization.cs deleted file mode 100644 index 4064a304ee6c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.Serialization.cs +++ /dev/null @@ -1,118 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceIntegratedVectorizationSource : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - } - - InternalAzureChatDataSourceIntegratedVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceIntegratedVectorizationSource)JsonModelCreateCore(ref reader, options); - - protected override DataSourceVectorizer JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceIntegratedVectorizationSource DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "integrated"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceIntegratedVectorizationSource(@type, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceIntegratedVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceIntegratedVectorizationSource)PersistableModelCreateCore(data, options); - - protected override DataSourceVectorizer PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceIntegratedVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceIntegratedVectorizationSource internalAzureChatDataSourceIntegratedVectorizationSource) - { - if (internalAzureChatDataSourceIntegratedVectorizationSource == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceIntegratedVectorizationSource, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceIntegratedVectorizationSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceIntegratedVectorizationSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.cs deleted file mode 100644 index b1a7e7e61087..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceIntegratedVectorizationSource.cs +++ /dev/null @@ -1,20 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceIntegratedVectorizationSource : DataSourceVectorizer - { - public InternalAzureChatDataSourceIntegratedVectorizationSource() : base("integrated") - { - } - - internal InternalAzureChatDataSourceIntegratedVectorizationSource(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) - { - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.Serialization.cs deleted file mode 100644 index b5754f58cf6f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,144 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions : IJsonModel - { - internal InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("key") != true) - { - writer.WritePropertyName("key"u8); - writer.WriteStringValue(Key); - } - if (_additionalBinaryDataProperties?.ContainsKey("key_id") != true) - { - writer.WritePropertyName("key_id"u8); - writer.WriteStringValue(KeyId); - } - } - - InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "key_and_key_id"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string key = default; - string keyId = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("key"u8)) - { - key = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("key_id"u8)) - { - keyId = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(@type, additionalBinaryDataProperties, key, keyId); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions internalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions) - { - if (internalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.cs deleted file mode 100644 index 0dd6b4a33973..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions.cs +++ /dev/null @@ -1,34 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(string key, string keyId) : base("key_and_key_id") - { - Argument.AssertNotNull(key, nameof(key)); - Argument.AssertNotNull(keyId, nameof(keyId)); - - Key = key; - KeyId = keyId; - } - - internal InternalAzureChatDataSourceKeyAndKeyIdAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties, string key, string keyId) : base(@type, additionalBinaryDataProperties) - { - Key = key; - KeyId = keyId; - } - - /// Gets the Key. - public string Key { get; set; } - - /// Gets the KeyId. - public string KeyId { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.Serialization.cs deleted file mode 100644 index 5e19ad8debf1..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceModelIdVectorizationSource : IJsonModel - { - internal InternalAzureChatDataSourceModelIdVectorizationSource() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("model_id") != true) - { - writer.WritePropertyName("model_id"u8); - writer.WriteStringValue(ModelId); - } - } - - InternalAzureChatDataSourceModelIdVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceModelIdVectorizationSource)JsonModelCreateCore(ref reader, options); - - protected override DataSourceVectorizer JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceModelIdVectorizationSource DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "model_id"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string modelId = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("model_id"u8)) - { - modelId = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceModelIdVectorizationSource(@type, additionalBinaryDataProperties, modelId); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceModelIdVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceModelIdVectorizationSource)PersistableModelCreateCore(data, options); - - protected override DataSourceVectorizer PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceModelIdVectorizationSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceModelIdVectorizationSource internalAzureChatDataSourceModelIdVectorizationSource) - { - if (internalAzureChatDataSourceModelIdVectorizationSource == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceModelIdVectorizationSource, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceModelIdVectorizationSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceModelIdVectorizationSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.cs deleted file mode 100644 index 2523ca56e4b2..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceModelIdVectorizationSource.cs +++ /dev/null @@ -1,28 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceModelIdVectorizationSource : DataSourceVectorizer - { - public InternalAzureChatDataSourceModelIdVectorizationSource(string modelId) : base("model_id") - { - Argument.AssertNotNull(modelId, nameof(modelId)); - - ModelId = modelId; - } - - internal InternalAzureChatDataSourceModelIdVectorizationSource(string @type, IDictionary additionalBinaryDataProperties, string modelId) : base(@type, additionalBinaryDataProperties) - { - ModelId = modelId; - } - - /// The embedding model build ID to use for vectorization. - public string ModelId { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs deleted file mode 100644 index 4bb24ad4201d..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,118 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - } - - InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "system_assigned_managed_identity"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(@type, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions internalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions) - { - if (internalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.cs deleted file mode 100644 index 2e6ddffbb1b9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions.cs +++ /dev/null @@ -1,20 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions() : base("system_assigned_managed_identity") - { - } - - internal InternalAzureChatDataSourceSystemAssignedManagedIdentityAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties) : base(@type, additionalBinaryDataProperties) - { - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs deleted file mode 100644 index d34ec6de681b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,133 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions : IJsonModel - { - internal InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("managed_identity_resource_id") != true) - { - writer.WritePropertyName("managed_identity_resource_id"u8); - writer.WriteStringValue(ManagedIdentityResourceId); - } - } - - InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "user_assigned_managed_identity"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string managedIdentityResourceId = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("managed_identity_resource_id"u8)) - { - managedIdentityResourceId = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(@type, additionalBinaryDataProperties, managedIdentityResourceId); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions internalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions) - { - if (internalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.cs deleted file mode 100644 index 787e66681e25..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions.cs +++ /dev/null @@ -1,28 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(string managedIdentityResourceId) : base("user_assigned_managed_identity") - { - Argument.AssertNotNull(managedIdentityResourceId, nameof(managedIdentityResourceId)); - - ManagedIdentityResourceId = managedIdentityResourceId; - } - - internal InternalAzureChatDataSourceUserAssignedManagedIdentityAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties, string managedIdentityResourceId) : base(@type, additionalBinaryDataProperties) - { - ManagedIdentityResourceId = managedIdentityResourceId; - } - - /// Gets the ManagedIdentityResourceId. - public string ManagedIdentityResourceId { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.Serialization.cs deleted file mode 100644 index c9ceed3e60ed..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,144 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions : IJsonModel - { - internal InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("username") != true) - { - writer.WritePropertyName("username"u8); - writer.WriteStringValue(Username); - } - if (_additionalBinaryDataProperties?.ContainsKey("password") != true) - { - writer.WritePropertyName("password"u8); - writer.WriteStringValue(Password); - } - } - - InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(document.RootElement, options); - } - - internal static InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "username_and_password"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - string username = default; - string password = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("username"u8)) - { - username = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("password"u8)) - { - password = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(@type, additionalBinaryDataProperties, username, password); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions internalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions) - { - if (internalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions == null) - { - return null; - } - return BinaryContent.Create(internalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.cs deleted file mode 100644 index 064772c9d7e2..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions.cs +++ /dev/null @@ -1,34 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions : DataSourceAuthentication - { - public InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(string username, string password) : base("username_and_password") - { - Argument.AssertNotNull(username, nameof(username)); - Argument.AssertNotNull(password, nameof(password)); - - Username = username; - Password = password; - } - - internal InternalAzureChatDataSourceUsernameAndPasswordAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties, string username, string password) : base(@type, additionalBinaryDataProperties) - { - Username = username; - Password = password; - } - - /// Gets the Username. - public string Username { get; set; } - - /// Gets the Password. - public string Password { get; set; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.Serialization.cs deleted file mode 100644 index d57188f9952d..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.Serialization.cs +++ /dev/null @@ -1,155 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterBlocklistIdResult : IJsonModel - { - internal InternalAzureContentFilterBlocklistIdResult() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistIdResult)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (_additionalBinaryDataProperties?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureContentFilterBlocklistIdResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureContentFilterBlocklistIdResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistIdResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterBlocklistIdResult(document.RootElement, options); - } - - internal static InternalAzureContentFilterBlocklistIdResult DeserializeInternalAzureContentFilterBlocklistIdResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string id = default; - bool filtered = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("id"u8)) - { - id = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("filtered"u8)) - { - filtered = prop.Value.GetBoolean(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureContentFilterBlocklistIdResult(id, filtered, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistIdResult)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureContentFilterBlocklistIdResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureContentFilterBlocklistIdResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureContentFilterBlocklistIdResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistIdResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureContentFilterBlocklistIdResult internalAzureContentFilterBlocklistIdResult) - { - if (internalAzureContentFilterBlocklistIdResult == null) - { - return null; - } - return BinaryContent.Create(internalAzureContentFilterBlocklistIdResult, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureContentFilterBlocklistIdResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterBlocklistIdResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.cs deleted file mode 100644 index ea761d8517a2..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistIdResult.cs +++ /dev/null @@ -1,41 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterBlocklistIdResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal InternalAzureContentFilterBlocklistIdResult(string id, bool filtered) - { - Id = id; - Filtered = filtered; - } - - internal InternalAzureContentFilterBlocklistIdResult(string id, bool filtered, IDictionary additionalBinaryDataProperties) - { - Id = id; - Filtered = filtered; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The ID of the custom blocklist associated with the filtered status. - public string Id { get; set; } - - /// Whether the associated blocklist resulted in the content being filtered. - public bool Filtered { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.Serialization.cs deleted file mode 100644 index 21bd3141df33..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.Serialization.cs +++ /dev/null @@ -1,155 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterBlocklistResultDetail : IJsonModel - { - internal InternalAzureContentFilterBlocklistResultDetail() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistResultDetail)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("filtered") != true) - { - writer.WritePropertyName("filtered"u8); - writer.WriteBooleanValue(Filtered); - } - if (_additionalBinaryDataProperties?.ContainsKey("id") != true) - { - writer.WritePropertyName("id"u8); - writer.WriteStringValue(Id); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureContentFilterBlocklistResultDetail IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureContentFilterBlocklistResultDetail JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistResultDetail)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterBlocklistResultDetail(document.RootElement, options); - } - - internal static InternalAzureContentFilterBlocklistResultDetail DeserializeInternalAzureContentFilterBlocklistResultDetail(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - bool filtered = default; - string id = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("filtered"u8)) - { - filtered = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("id"u8)) - { - id = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureContentFilterBlocklistResultDetail(filtered, id, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistResultDetail)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureContentFilterBlocklistResultDetail IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureContentFilterBlocklistResultDetail PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureContentFilterBlocklistResultDetail(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterBlocklistResultDetail)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureContentFilterBlocklistResultDetail internalAzureContentFilterBlocklistResultDetail) - { - if (internalAzureContentFilterBlocklistResultDetail == null) - { - return null; - } - return BinaryContent.Create(internalAzureContentFilterBlocklistResultDetail, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureContentFilterBlocklistResultDetail(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterBlocklistResultDetail(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.cs deleted file mode 100644 index 8bfa248fcbe2..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterBlocklistResultDetail.cs +++ /dev/null @@ -1,41 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterBlocklistResultDetail - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal InternalAzureContentFilterBlocklistResultDetail(bool filtered, string id) - { - Filtered = filtered; - Id = id; - } - - internal InternalAzureContentFilterBlocklistResultDetail(bool filtered, string id, IDictionary additionalBinaryDataProperties) - { - Filtered = filtered; - Id = id; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// A value indicating whether the blocklist produced a filtering action. - public bool Filtered { get; set; } - - /// The ID of the custom blocklist evaluated. - public string Id { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.Serialization.cs deleted file mode 100644 index 4abb04256be1..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.Serialization.cs +++ /dev/null @@ -1,155 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterResultForChoiceError : IJsonModel - { - internal InternalAzureContentFilterResultForChoiceError() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForChoiceError)} does not support writing '{format}' format."); - } - if (_additionalBinaryDataProperties?.ContainsKey("code") != true) - { - writer.WritePropertyName("code"u8); - writer.WriteNumberValue(Code); - } - if (_additionalBinaryDataProperties?.ContainsKey("message") != true) - { - writer.WritePropertyName("message"u8); - writer.WriteStringValue(Message); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureContentFilterResultForChoiceError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureContentFilterResultForChoiceError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForChoiceError)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterResultForChoiceError(document.RootElement, options); - } - - internal static InternalAzureContentFilterResultForChoiceError DeserializeInternalAzureContentFilterResultForChoiceError(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int code = default; - string message = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("code"u8)) - { - code = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("message"u8)) - { - message = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureContentFilterResultForChoiceError(code, message, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForChoiceError)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureContentFilterResultForChoiceError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureContentFilterResultForChoiceError PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureContentFilterResultForChoiceError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForChoiceError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureContentFilterResultForChoiceError internalAzureContentFilterResultForChoiceError) - { - if (internalAzureContentFilterResultForChoiceError == null) - { - return null; - } - return BinaryContent.Create(internalAzureContentFilterResultForChoiceError, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureContentFilterResultForChoiceError(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterResultForChoiceError(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.cs deleted file mode 100644 index de893f36f991..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForChoiceError.cs +++ /dev/null @@ -1,41 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterResultForChoiceError - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal InternalAzureContentFilterResultForChoiceError(int code, string message) - { - Code = code; - Message = message; - } - - internal InternalAzureContentFilterResultForChoiceError(int code, string message, IDictionary additionalBinaryDataProperties) - { - Code = code; - Message = message; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// A distinct, machine-readable code associated with the error. - public int Code { get; set; } - - /// A human-readable message associated with the error. - public string Message { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.Serialization.cs deleted file mode 100644 index 2a95abe6d0d9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.Serialization.cs +++ /dev/null @@ -1,270 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterResultForPromptContentFilterResults : IJsonModel - { - internal InternalAzureContentFilterResultForPromptContentFilterResults() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Sexual) && _additionalBinaryDataProperties?.ContainsKey("sexual") != true) - { - writer.WritePropertyName("sexual"u8); - writer.WriteObjectValue(Sexual, options); - } - if (Optional.IsDefined(Hate) && _additionalBinaryDataProperties?.ContainsKey("hate") != true) - { - writer.WritePropertyName("hate"u8); - writer.WriteObjectValue(Hate, options); - } - if (Optional.IsDefined(Violence) && _additionalBinaryDataProperties?.ContainsKey("violence") != true) - { - writer.WritePropertyName("violence"u8); - writer.WriteObjectValue(Violence, options); - } - if (Optional.IsDefined(SelfHarm) && _additionalBinaryDataProperties?.ContainsKey("self_harm") != true) - { - writer.WritePropertyName("self_harm"u8); - writer.WriteObjectValue(SelfHarm, options); - } - if (Optional.IsDefined(Profanity) && _additionalBinaryDataProperties?.ContainsKey("profanity") != true) - { - writer.WritePropertyName("profanity"u8); - writer.WriteObjectValue(Profanity, options); - } - if (Optional.IsDefined(CustomBlocklists) && _additionalBinaryDataProperties?.ContainsKey("custom_blocklists") != true) - { - writer.WritePropertyName("custom_blocklists"u8); - writer.WriteObjectValue(CustomBlocklists, options); - } - if (Optional.IsDefined(Error) && _additionalBinaryDataProperties?.ContainsKey("error") != true) - { - writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("jailbreak") != true) - { - writer.WritePropertyName("jailbreak"u8); - writer.WriteObjectValue(Jailbreak, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("indirect_attack") != true) - { - writer.WritePropertyName("indirect_attack"u8); - writer.WriteObjectValue(IndirectAttack, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureContentFilterResultForPromptContentFilterResults IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureContentFilterResultForPromptContentFilterResults JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(document.RootElement, options); - } - - internal static InternalAzureContentFilterResultForPromptContentFilterResults DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult selfHarm = default; - ContentFilterDetectionResult profanity = default; - ContentFilterBlocklistResult customBlocklists = default; - InternalAzureContentFilterResultForChoiceError error = default; - ContentFilterDetectionResult jailbreak = default; - ContentFilterDetectionResult indirectAttack = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("sexual"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("hate"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("violence"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("self_harm"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("profanity"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(prop.Value, options); - continue; - } - if (prop.NameEquals("custom_blocklists"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - customBlocklists = ContentFilterBlocklistResult.DeserializeContentFilterBlocklistResult(prop.Value, options); - continue; - } - if (prop.NameEquals("error"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = InternalAzureContentFilterResultForChoiceError.DeserializeInternalAzureContentFilterResultForChoiceError(prop.Value, options); - continue; - } - if (prop.NameEquals("jailbreak"u8)) - { - jailbreak = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(prop.Value, options); - continue; - } - if (prop.NameEquals("indirect_attack"u8)) - { - indirectAttack = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureContentFilterResultForPromptContentFilterResults( - sexual, - hate, - violence, - selfHarm, - profanity, - customBlocklists, - error, - jailbreak, - indirectAttack, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureContentFilterResultForPromptContentFilterResults IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureContentFilterResultForPromptContentFilterResults PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureContentFilterResultForPromptContentFilterResults)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureContentFilterResultForPromptContentFilterResults internalAzureContentFilterResultForPromptContentFilterResults) - { - if (internalAzureContentFilterResultForPromptContentFilterResults == null) - { - return null; - } - return BinaryContent.Create(internalAzureContentFilterResultForPromptContentFilterResults, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureContentFilterResultForPromptContentFilterResults(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.cs deleted file mode 100644 index f13b6ea14d31..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureContentFilterResultForPromptContentFilterResults.cs +++ /dev/null @@ -1,96 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureContentFilterResultForPromptContentFilterResults - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal InternalAzureContentFilterResultForPromptContentFilterResults(ContentFilterDetectionResult jailbreak, ContentFilterDetectionResult indirectAttack) - { - Jailbreak = jailbreak; - IndirectAttack = indirectAttack; - } - - internal InternalAzureContentFilterResultForPromptContentFilterResults(ContentFilterSeverityResult sexual, ContentFilterSeverityResult hate, ContentFilterSeverityResult violence, ContentFilterSeverityResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterBlocklistResult customBlocklists, InternalAzureContentFilterResultForChoiceError error, ContentFilterDetectionResult jailbreak, ContentFilterDetectionResult indirectAttack, IDictionary additionalBinaryDataProperties) - { - Sexual = sexual; - Hate = hate; - Violence = violence; - SelfHarm = selfHarm; - Profanity = profanity; - CustomBlocklists = customBlocklists; - Error = error; - Jailbreak = jailbreak; - IndirectAttack = indirectAttack; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - public ContentFilterSeverityResult Sexual { get; set; } - - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on 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. - /// - public ContentFilterSeverityResult Hate { get; set; } - - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - public ContentFilterSeverityResult Violence { get; set; } - - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - public ContentFilterSeverityResult SelfHarm { get; set; } - - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - public ContentFilterDetectionResult Profanity { get; set; } - - /// A collection of binary filtering outcomes for configured custom blocklists. - public ContentFilterBlocklistResult CustomBlocklists { get; set; } - - /// If present, details about an error that prevented content filtering from completing its evaluation. - public InternalAzureContentFilterResultForChoiceError Error { get; set; } - - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - public ContentFilterDetectionResult Jailbreak { get; set; } - - /// - /// A detection result that describes attacks on systems powered by Generative AI models that can happen every time - /// an application processes information that wasn’t directly authored by either the developer of the application or - /// the user. - /// - public ContentFilterDetectionResult IndirectAttack { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.Serialization.cs deleted file mode 100644 index 1b789ba9d41f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.Serialization.cs +++ /dev/null @@ -1,325 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureCosmosDBChatDataSourceParameters : IJsonModel - { - internal InternalAzureCosmosDBChatDataSourceParameters() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureCosmosDBChatDataSourceParameters)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(TopNDocuments) && _additionalBinaryDataProperties?.ContainsKey("top_n_documents") != true) - { - writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); - } - if (Optional.IsDefined(InScope) && _additionalBinaryDataProperties?.ContainsKey("in_scope") != true) - { - writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); - } - if (Optional.IsDefined(Strictness) && _additionalBinaryDataProperties?.ContainsKey("strictness") != true) - { - writer.WritePropertyName("strictness"u8); - writer.WriteNumberValue(Strictness.Value); - } - if (Optional.IsDefined(MaxSearchQueries) && _additionalBinaryDataProperties?.ContainsKey("max_search_queries") != true) - { - writer.WritePropertyName("max_search_queries"u8); - writer.WriteNumberValue(MaxSearchQueries.Value); - } - if (Optional.IsDefined(AllowPartialResult) && _additionalBinaryDataProperties?.ContainsKey("allow_partial_result") != true) - { - writer.WritePropertyName("allow_partial_result"u8); - writer.WriteBooleanValue(AllowPartialResult.Value); - } - if (_additionalBinaryDataProperties?.ContainsKey("container_name") != true) - { - writer.WritePropertyName("container_name"u8); - writer.WriteStringValue(ContainerName); - } - if (_additionalBinaryDataProperties?.ContainsKey("database_name") != true) - { - writer.WritePropertyName("database_name"u8); - writer.WriteStringValue(DatabaseName); - } - if (_additionalBinaryDataProperties?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (_additionalBinaryDataProperties?.ContainsKey("authentication") != true) - { - writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("fields_mapping") != true) - { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); - } - if (Optional.IsCollectionDefined(_internalIncludeContexts) && _additionalBinaryDataProperties?.ContainsKey("include_contexts") != true) - { - writer.WritePropertyName("include_contexts"u8); - writer.WriteStartArray(); - foreach (string item in _internalIncludeContexts) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureCosmosDBChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureCosmosDBChatDataSourceParameters JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureCosmosDBChatDataSourceParameters)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureCosmosDBChatDataSourceParameters(document.RootElement, options); - } - - internal static InternalAzureCosmosDBChatDataSourceParameters DeserializeInternalAzureCosmosDBChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? topNDocuments = default; - bool? inScope = default; - int? strictness = default; - int? maxSearchQueries = default; - bool? allowPartialResult = default; - string containerName = default; - string databaseName = default; - string indexName = default; - DataSourceAuthentication authentication = default; - DataSourceFieldMappings fieldMappings = default; - DataSourceVectorizer vectorizationSource = default; - IList internalIncludeContexts = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("top_n_documents"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - topNDocuments = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("in_scope"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - inScope = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("strictness"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - strictness = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("max_search_queries"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - maxSearchQueries = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("allow_partial_result"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allowPartialResult = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("container_name"u8)) - { - containerName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("database_name"u8)) - { - databaseName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("index_name"u8)) - { - indexName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(prop.Value, options); - continue; - } - if (prop.NameEquals("fields_mapping"u8)) - { - fieldMappings = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(prop.Value, options); - continue; - } - if (prop.NameEquals("embedding_dependency"u8)) - { - vectorizationSource = DataSourceVectorizer.DeserializeDataSourceVectorizer(prop.Value, options); - continue; - } - if (prop.NameEquals("include_contexts"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - internalIncludeContexts = array; - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureCosmosDBChatDataSourceParameters( - topNDocuments, - inScope, - strictness, - maxSearchQueries, - allowPartialResult, - containerName, - databaseName, - indexName, - authentication, - fieldMappings, - vectorizationSource, - internalIncludeContexts, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureCosmosDBChatDataSourceParameters)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureCosmosDBChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureCosmosDBChatDataSourceParameters PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureCosmosDBChatDataSourceParameters(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureCosmosDBChatDataSourceParameters)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureCosmosDBChatDataSourceParameters internalAzureCosmosDBChatDataSourceParameters) - { - if (internalAzureCosmosDBChatDataSourceParameters == null) - { - return null; - } - return BinaryContent.Create(internalAzureCosmosDBChatDataSourceParameters, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureCosmosDBChatDataSourceParameters(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureCosmosDBChatDataSourceParameters(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.cs deleted file mode 100644 index 60b88b2ab5aa..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureCosmosDBChatDataSourceParameters.cs +++ /dev/null @@ -1,91 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureCosmosDBChatDataSourceParameters - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - public InternalAzureCosmosDBChatDataSourceParameters(string containerName, string databaseName, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceVectorizer vectorizationSource) - { - Argument.AssertNotNull(containerName, nameof(containerName)); - Argument.AssertNotNull(databaseName, nameof(databaseName)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - Argument.AssertNotNull(fieldMappings, nameof(fieldMappings)); - Argument.AssertNotNull(vectorizationSource, nameof(vectorizationSource)); - - ContainerName = containerName; - DatabaseName = databaseName; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - VectorizationSource = vectorizationSource; - _internalIncludeContexts = new ChangeTrackingList(); - } - - internal InternalAzureCosmosDBChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, string containerName, string databaseName, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceVectorizer vectorizationSource, IList internalIncludeContexts, IDictionary additionalBinaryDataProperties) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - ContainerName = containerName; - DatabaseName = databaseName; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - VectorizationSource = vectorizationSource; - _internalIncludeContexts = internalIncludeContexts; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - - /// Gets the ContainerName. - public string ContainerName { get; set; } - - /// Gets the DatabaseName. - public string DatabaseName { get; set; } - - /// Gets the IndexName. - public string IndexName { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.Serialization.cs deleted file mode 100644 index b52b4bf0dc45..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureOpenAIChatErrorInnerError : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureOpenAIChatErrorInnerError)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code.Value.ToString()); - } - if (Optional.IsDefined(RevisedPrompt) && _additionalBinaryDataProperties?.ContainsKey("revised_prompt") != true) - { - writer.WritePropertyName("revised_prompt"u8); - writer.WriteStringValue(RevisedPrompt); - } - if (Optional.IsDefined(ContentFilterResults) && _additionalBinaryDataProperties?.ContainsKey("content_filter_results") != true) - { - writer.WritePropertyName("content_filter_results"u8); - writer.WriteObjectValue(ContentFilterResults, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureOpenAIChatErrorInnerError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureOpenAIChatErrorInnerError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureOpenAIChatErrorInnerError)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureOpenAIChatErrorInnerError(document.RootElement, options); - } - - internal static InternalAzureOpenAIChatErrorInnerError DeserializeInternalAzureOpenAIChatErrorInnerError(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalAzureOpenAIChatErrorInnerErrorCode? code = default; - string revisedPrompt = default; - RequestContentFilterResult contentFilterResults = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("code"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - code = new InternalAzureOpenAIChatErrorInnerErrorCode(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("revised_prompt"u8)) - { - revisedPrompt = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("content_filter_results"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - contentFilterResults = RequestContentFilterResult.DeserializeRequestContentFilterResult(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureOpenAIChatErrorInnerError(code, revisedPrompt, contentFilterResults, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureOpenAIChatErrorInnerError)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureOpenAIChatErrorInnerError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureOpenAIChatErrorInnerError PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureOpenAIChatErrorInnerError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureOpenAIChatErrorInnerError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureOpenAIChatErrorInnerError internalAzureOpenAIChatErrorInnerError) - { - if (internalAzureOpenAIChatErrorInnerError == null) - { - return null; - } - return BinaryContent.Create(internalAzureOpenAIChatErrorInnerError, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureOpenAIChatErrorInnerError(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureOpenAIChatErrorInnerError(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.cs deleted file mode 100644 index e145266f8d23..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerError.cs +++ /dev/null @@ -1,43 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureOpenAIChatErrorInnerError - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal InternalAzureOpenAIChatErrorInnerError() - { - } - - internal InternalAzureOpenAIChatErrorInnerError(InternalAzureOpenAIChatErrorInnerErrorCode? code, string revisedPrompt, RequestContentFilterResult contentFilterResults, IDictionary additionalBinaryDataProperties) - { - Code = code; - RevisedPrompt = revisedPrompt; - ContentFilterResults = contentFilterResults; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The code associated with the inner error. - public InternalAzureOpenAIChatErrorInnerErrorCode? Code { get; set; } - - /// If applicable, the modified prompt used for generation. - public string RevisedPrompt { get; set; } - - /// The content filter result details associated with the inner error. - public RequestContentFilterResult ContentFilterResults { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerErrorCode.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerErrorCode.cs deleted file mode 100644 index e7d0a4a2b932..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIChatErrorInnerErrorCode.cs +++ /dev/null @@ -1,44 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI -{ - internal readonly partial struct InternalAzureOpenAIChatErrorInnerErrorCode : IEquatable - { - private readonly string _value; - /// ResponsibleAIPolicyViolation. - private const string ResponsibleAIPolicyViolationValue = "ResponsibleAIPolicyViolation"; - - public InternalAzureOpenAIChatErrorInnerErrorCode(string value) - { - Argument.AssertNotNull(value, nameof(value)); - - _value = value; - } - - /// ResponsibleAIPolicyViolation. - public static InternalAzureOpenAIChatErrorInnerErrorCode ResponsibleAIPolicyViolation { get; set; } = new InternalAzureOpenAIChatErrorInnerErrorCode(ResponsibleAIPolicyViolationValue); - - public static bool operator ==(InternalAzureOpenAIChatErrorInnerErrorCode left, InternalAzureOpenAIChatErrorInnerErrorCode right) => left.Equals(right); - - public static bool operator !=(InternalAzureOpenAIChatErrorInnerErrorCode left, InternalAzureOpenAIChatErrorInnerErrorCode right) => !left.Equals(right); - - public static implicit operator InternalAzureOpenAIChatErrorInnerErrorCode(string value) => new InternalAzureOpenAIChatErrorInnerErrorCode(value); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAzureOpenAIChatErrorInnerErrorCode other && Equals(other); - - public bool Equals(InternalAzureOpenAIChatErrorInnerErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.Serialization.cs deleted file mode 100644 index 38bf4ea6cbcd..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.Serialization.cs +++ /dev/null @@ -1,170 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureOpenAIDalleErrorInnerError : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureOpenAIDalleErrorInnerError)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Code) && _additionalBinaryDataProperties?.ContainsKey("code") != true) - { - writer.WritePropertyName("code"u8); - writer.WriteStringValue(Code.Value.ToString()); - } - if (Optional.IsDefined(RevisedPrompt) && _additionalBinaryDataProperties?.ContainsKey("revised_prompt") != true) - { - writer.WritePropertyName("revised_prompt"u8); - writer.WriteStringValue(RevisedPrompt); - } - if (Optional.IsDefined(ContentFilterResults) && _additionalBinaryDataProperties?.ContainsKey("content_filter_results") != true) - { - writer.WritePropertyName("content_filter_results"u8); - writer.WriteObjectValue(ContentFilterResults, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureOpenAIDalleErrorInnerError IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureOpenAIDalleErrorInnerError JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureOpenAIDalleErrorInnerError)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureOpenAIDalleErrorInnerError(document.RootElement, options); - } - - internal static InternalAzureOpenAIDalleErrorInnerError DeserializeInternalAzureOpenAIDalleErrorInnerError(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - InternalAzureOpenAIDalleErrorInnerErrorCode? code = default; - string revisedPrompt = default; - RequestImageContentFilterResult contentFilterResults = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("code"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - code = new InternalAzureOpenAIDalleErrorInnerErrorCode(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("revised_prompt"u8)) - { - revisedPrompt = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("content_filter_results"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - contentFilterResults = RequestImageContentFilterResult.DeserializeRequestImageContentFilterResult(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureOpenAIDalleErrorInnerError(code, revisedPrompt, contentFilterResults, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureOpenAIDalleErrorInnerError)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureOpenAIDalleErrorInnerError IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureOpenAIDalleErrorInnerError PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureOpenAIDalleErrorInnerError(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureOpenAIDalleErrorInnerError)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureOpenAIDalleErrorInnerError internalAzureOpenAIDalleErrorInnerError) - { - if (internalAzureOpenAIDalleErrorInnerError == null) - { - return null; - } - return BinaryContent.Create(internalAzureOpenAIDalleErrorInnerError, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureOpenAIDalleErrorInnerError(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureOpenAIDalleErrorInnerError(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.cs deleted file mode 100644 index 297fb1c94110..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerError.cs +++ /dev/null @@ -1,43 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - internal partial class InternalAzureOpenAIDalleErrorInnerError - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal InternalAzureOpenAIDalleErrorInnerError() - { - } - - internal InternalAzureOpenAIDalleErrorInnerError(InternalAzureOpenAIDalleErrorInnerErrorCode? code, string revisedPrompt, RequestImageContentFilterResult contentFilterResults, IDictionary additionalBinaryDataProperties) - { - Code = code; - RevisedPrompt = revisedPrompt; - ContentFilterResults = contentFilterResults; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The code associated with the inner error. - public InternalAzureOpenAIDalleErrorInnerErrorCode? Code { get; set; } - - /// If applicable, the modified prompt used for generation. - public string RevisedPrompt { get; set; } - - /// The content filter result details associated with the inner error. - public RequestImageContentFilterResult ContentFilterResults { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerErrorCode.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerErrorCode.cs deleted file mode 100644 index 435d4d34ca4c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureOpenAIDalleErrorInnerErrorCode.cs +++ /dev/null @@ -1,44 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; - -namespace Azure.AI.OpenAI -{ - internal readonly partial struct InternalAzureOpenAIDalleErrorInnerErrorCode : IEquatable - { - private readonly string _value; - /// ResponsibleAIPolicyViolation. - private const string ResponsibleAIPolicyViolationValue = "ResponsibleAIPolicyViolation"; - - public InternalAzureOpenAIDalleErrorInnerErrorCode(string value) - { - Argument.AssertNotNull(value, nameof(value)); - - _value = value; - } - - /// ResponsibleAIPolicyViolation. - public static InternalAzureOpenAIDalleErrorInnerErrorCode ResponsibleAIPolicyViolation { get; set; } = new InternalAzureOpenAIDalleErrorInnerErrorCode(ResponsibleAIPolicyViolationValue); - - public static bool operator ==(InternalAzureOpenAIDalleErrorInnerErrorCode left, InternalAzureOpenAIDalleErrorInnerErrorCode right) => left.Equals(right); - - public static bool operator !=(InternalAzureOpenAIDalleErrorInnerErrorCode left, InternalAzureOpenAIDalleErrorInnerErrorCode right) => !left.Equals(right); - - public static implicit operator InternalAzureOpenAIDalleErrorInnerErrorCode(string value) => new InternalAzureOpenAIDalleErrorInnerErrorCode(value); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAzureOpenAIDalleErrorInnerErrorCode other && Equals(other); - - public bool Equals(InternalAzureOpenAIDalleErrorInnerErrorCode other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.Serialization.cs deleted file mode 100644 index 93766d7aacb3..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.Serialization.cs +++ /dev/null @@ -1,361 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureSearchChatDataSourceParameters : IJsonModel - { - internal InternalAzureSearchChatDataSourceParameters() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureSearchChatDataSourceParameters)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(TopNDocuments) && _additionalBinaryDataProperties?.ContainsKey("top_n_documents") != true) - { - writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); - } - if (Optional.IsDefined(InScope) && _additionalBinaryDataProperties?.ContainsKey("in_scope") != true) - { - writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); - } - if (Optional.IsDefined(Strictness) && _additionalBinaryDataProperties?.ContainsKey("strictness") != true) - { - writer.WritePropertyName("strictness"u8); - writer.WriteNumberValue(Strictness.Value); - } - if (Optional.IsDefined(MaxSearchQueries) && _additionalBinaryDataProperties?.ContainsKey("max_search_queries") != true) - { - writer.WritePropertyName("max_search_queries"u8); - writer.WriteNumberValue(MaxSearchQueries.Value); - } - if (Optional.IsDefined(AllowPartialResult) && _additionalBinaryDataProperties?.ContainsKey("allow_partial_result") != true) - { - writer.WritePropertyName("allow_partial_result"u8); - writer.WriteBooleanValue(AllowPartialResult.Value); - } - if (_additionalBinaryDataProperties?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint.AbsoluteUri); - } - if (_additionalBinaryDataProperties?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (Optional.IsDefined(SemanticConfiguration) && _additionalBinaryDataProperties?.ContainsKey("semantic_configuration") != true) - { - writer.WritePropertyName("semantic_configuration"u8); - writer.WriteStringValue(SemanticConfiguration); - } - if (Optional.IsDefined(Filter) && _additionalBinaryDataProperties?.ContainsKey("filter") != true) - { - writer.WritePropertyName("filter"u8); - writer.WriteStringValue(Filter); - } - if (_additionalBinaryDataProperties?.ContainsKey("authentication") != true) - { - writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (Optional.IsDefined(FieldMappings) && _additionalBinaryDataProperties?.ContainsKey("fields_mapping") != true) - { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); - } - if (Optional.IsDefined(QueryType) && _additionalBinaryDataProperties?.ContainsKey("query_type") != true) - { - writer.WritePropertyName("query_type"u8); - writer.WriteStringValue(QueryType.Value.ToString()); - } - if (Optional.IsDefined(VectorizationSource) && _additionalBinaryDataProperties?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); - } - if (Optional.IsCollectionDefined(_internalIncludeContexts) && _additionalBinaryDataProperties?.ContainsKey("include_contexts") != true) - { - writer.WritePropertyName("include_contexts"u8); - writer.WriteStartArray(); - foreach (string item in _internalIncludeContexts) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalAzureSearchChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalAzureSearchChatDataSourceParameters JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalAzureSearchChatDataSourceParameters)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalAzureSearchChatDataSourceParameters(document.RootElement, options); - } - - internal static InternalAzureSearchChatDataSourceParameters DeserializeInternalAzureSearchChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? topNDocuments = default; - bool? inScope = default; - int? strictness = default; - int? maxSearchQueries = default; - bool? allowPartialResult = default; - Uri endpoint = default; - string indexName = default; - string semanticConfiguration = default; - string filter = default; - DataSourceAuthentication authentication = default; - DataSourceFieldMappings fieldMappings = default; - DataSourceQueryType? queryType = default; - DataSourceVectorizer vectorizationSource = default; - IList internalIncludeContexts = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("top_n_documents"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - topNDocuments = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("in_scope"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - inScope = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("strictness"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - strictness = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("max_search_queries"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - maxSearchQueries = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("allow_partial_result"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allowPartialResult = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("endpoint"u8)) - { - endpoint = new Uri(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("index_name"u8)) - { - indexName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("semantic_configuration"u8)) - { - semanticConfiguration = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("filter"u8)) - { - filter = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(prop.Value, options); - continue; - } - if (prop.NameEquals("fields_mapping"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - fieldMappings = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(prop.Value, options); - continue; - } - if (prop.NameEquals("query_type"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - queryType = new DataSourceQueryType(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("embedding_dependency"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - vectorizationSource = DataSourceVectorizer.DeserializeDataSourceVectorizer(prop.Value, options); - continue; - } - if (prop.NameEquals("include_contexts"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - internalIncludeContexts = array; - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalAzureSearchChatDataSourceParameters( - topNDocuments, - inScope, - strictness, - maxSearchQueries, - allowPartialResult, - endpoint, - indexName, - semanticConfiguration, - filter, - authentication, - fieldMappings, - queryType, - vectorizationSource, - internalIncludeContexts, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalAzureSearchChatDataSourceParameters)} does not support writing '{options.Format}' format."); - } - } - - InternalAzureSearchChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalAzureSearchChatDataSourceParameters PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalAzureSearchChatDataSourceParameters(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalAzureSearchChatDataSourceParameters)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalAzureSearchChatDataSourceParameters internalAzureSearchChatDataSourceParameters) - { - if (internalAzureSearchChatDataSourceParameters == null) - { - return null; - } - return BinaryContent.Create(internalAzureSearchChatDataSourceParameters, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalAzureSearchChatDataSourceParameters(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalAzureSearchChatDataSourceParameters(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.cs deleted file mode 100644 index b330998a523f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParameters.cs +++ /dev/null @@ -1,90 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalAzureSearchChatDataSourceParameters - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - public InternalAzureSearchChatDataSourceParameters(Uri endpoint, string indexName, DataSourceAuthentication authentication) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - - Endpoint = endpoint; - IndexName = indexName; - Authentication = authentication; - _internalIncludeContexts = new ChangeTrackingList(); - } - - internal InternalAzureSearchChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, Uri endpoint, string indexName, string semanticConfiguration, string filter, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceQueryType? queryType, DataSourceVectorizer vectorizationSource, IList internalIncludeContexts, IDictionary additionalBinaryDataProperties) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - Endpoint = endpoint; - IndexName = indexName; - SemanticConfiguration = semanticConfiguration; - Filter = filter; - Authentication = authentication; - FieldMappings = fieldMappings; - QueryType = queryType; - VectorizationSource = vectorizationSource; - _internalIncludeContexts = internalIncludeContexts; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - - /// The absolute endpoint path for the Azure Search resource to use. - public Uri Endpoint { get; set; } - - /// The name of the index to use, as specified in the Azure Search resource. - public string IndexName { get; set; } - - /// Additional semantic configuration for the query. - public string SemanticConfiguration { get; set; } - - /// A filter to apply to the search. - public string Filter { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParametersIncludeContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParametersIncludeContext.cs deleted file mode 100644 index 90c9028d2b58..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalAzureSearchChatDataSourceParametersIncludeContext.cs +++ /dev/null @@ -1,52 +0,0 @@ -// - -#nullable disable - -using System; -using System.ComponentModel; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal readonly partial struct InternalAzureSearchChatDataSourceParametersIncludeContext : IEquatable - { - private readonly string _value; - private const string CitationsValue = "citations"; - private const string IntentValue = "intent"; - private const string AllRetrievedDocumentsValue = "all_retrieved_documents"; - - public InternalAzureSearchChatDataSourceParametersIncludeContext(string value) - { - Argument.AssertNotNull(value, nameof(value)); - - _value = value; - } - - /// Gets the Citations. - public static InternalAzureSearchChatDataSourceParametersIncludeContext Citations { get; set; } = new InternalAzureSearchChatDataSourceParametersIncludeContext(CitationsValue); - - /// Gets the Intent. - public static InternalAzureSearchChatDataSourceParametersIncludeContext Intent { get; set; } = new InternalAzureSearchChatDataSourceParametersIncludeContext(IntentValue); - - /// Gets the AllRetrievedDocuments. - public static InternalAzureSearchChatDataSourceParametersIncludeContext AllRetrievedDocuments { get; set; } = new InternalAzureSearchChatDataSourceParametersIncludeContext(AllRetrievedDocumentsValue); - - public static bool operator ==(InternalAzureSearchChatDataSourceParametersIncludeContext left, InternalAzureSearchChatDataSourceParametersIncludeContext right) => left.Equals(right); - - public static bool operator !=(InternalAzureSearchChatDataSourceParametersIncludeContext left, InternalAzureSearchChatDataSourceParametersIncludeContext right) => !left.Equals(right); - - public static implicit operator InternalAzureSearchChatDataSourceParametersIncludeContext(string value) => new InternalAzureSearchChatDataSourceParametersIncludeContext(value); - - [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => obj is InternalAzureSearchChatDataSourceParametersIncludeContext other && Equals(other); - - public bool Equals(InternalAzureSearchChatDataSourceParametersIncludeContext other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); - - /// - [EditorBrowsable(EditorBrowsableState.Never)] - public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; - - /// - public override string ToString() => _value; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.Serialization.cs deleted file mode 100644 index ac57dcaa2b60..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.Serialization.cs +++ /dev/null @@ -1,337 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalElasticsearchChatDataSourceParameters : IJsonModel - { - internal InternalElasticsearchChatDataSourceParameters() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalElasticsearchChatDataSourceParameters)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(TopNDocuments) && _additionalBinaryDataProperties?.ContainsKey("top_n_documents") != true) - { - writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); - } - if (Optional.IsDefined(InScope) && _additionalBinaryDataProperties?.ContainsKey("in_scope") != true) - { - writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); - } - if (Optional.IsDefined(Strictness) && _additionalBinaryDataProperties?.ContainsKey("strictness") != true) - { - writer.WritePropertyName("strictness"u8); - writer.WriteNumberValue(Strictness.Value); - } - if (Optional.IsDefined(MaxSearchQueries) && _additionalBinaryDataProperties?.ContainsKey("max_search_queries") != true) - { - writer.WritePropertyName("max_search_queries"u8); - writer.WriteNumberValue(MaxSearchQueries.Value); - } - if (Optional.IsDefined(AllowPartialResult) && _additionalBinaryDataProperties?.ContainsKey("allow_partial_result") != true) - { - writer.WritePropertyName("allow_partial_result"u8); - writer.WriteBooleanValue(AllowPartialResult.Value); - } - if (_additionalBinaryDataProperties?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint.AbsoluteUri); - } - if (_additionalBinaryDataProperties?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (Optional.IsCollectionDefined(InternalIncludeContexts) && _additionalBinaryDataProperties?.ContainsKey("include_contexts") != true) - { - writer.WritePropertyName("include_contexts"u8); - writer.WriteStartArray(); - foreach (string item in InternalIncludeContexts) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (_additionalBinaryDataProperties?.ContainsKey("authentication") != true) - { - writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (Optional.IsDefined(FieldMappings) && _additionalBinaryDataProperties?.ContainsKey("fields_mapping") != true) - { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); - } - if (Optional.IsDefined(QueryType) && _additionalBinaryDataProperties?.ContainsKey("query_type") != true) - { - writer.WritePropertyName("query_type"u8); - writer.WriteStringValue(QueryType.Value.ToString()); - } - if (Optional.IsDefined(VectorizationSource) && _additionalBinaryDataProperties?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalElasticsearchChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalElasticsearchChatDataSourceParameters JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalElasticsearchChatDataSourceParameters)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalElasticsearchChatDataSourceParameters(document.RootElement, options); - } - - internal static InternalElasticsearchChatDataSourceParameters DeserializeInternalElasticsearchChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? topNDocuments = default; - bool? inScope = default; - int? strictness = default; - int? maxSearchQueries = default; - bool? allowPartialResult = default; - Uri endpoint = default; - string indexName = default; - IList internalIncludeContexts = default; - DataSourceAuthentication authentication = default; - DataSourceFieldMappings fieldMappings = default; - DataSourceQueryType? queryType = default; - DataSourceVectorizer vectorizationSource = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("top_n_documents"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - topNDocuments = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("in_scope"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - inScope = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("strictness"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - strictness = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("max_search_queries"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - maxSearchQueries = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("allow_partial_result"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allowPartialResult = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("endpoint"u8)) - { - endpoint = new Uri(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("index_name"u8)) - { - indexName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("include_contexts"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - internalIncludeContexts = array; - continue; - } - if (prop.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(prop.Value, options); - continue; - } - if (prop.NameEquals("fields_mapping"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - fieldMappings = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(prop.Value, options); - continue; - } - if (prop.NameEquals("query_type"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - queryType = new DataSourceQueryType(prop.Value.GetString()); - continue; - } - if (prop.NameEquals("embedding_dependency"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - vectorizationSource = DataSourceVectorizer.DeserializeDataSourceVectorizer(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalElasticsearchChatDataSourceParameters( - topNDocuments, - inScope, - strictness, - maxSearchQueries, - allowPartialResult, - endpoint, - indexName, - internalIncludeContexts ?? new ChangeTrackingList(), - authentication, - fieldMappings, - queryType, - vectorizationSource, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalElasticsearchChatDataSourceParameters)} does not support writing '{options.Format}' format."); - } - } - - InternalElasticsearchChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalElasticsearchChatDataSourceParameters PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalElasticsearchChatDataSourceParameters(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalElasticsearchChatDataSourceParameters)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalElasticsearchChatDataSourceParameters internalElasticsearchChatDataSourceParameters) - { - if (internalElasticsearchChatDataSourceParameters == null) - { - return null; - } - return BinaryContent.Create(internalElasticsearchChatDataSourceParameters, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalElasticsearchChatDataSourceParameters(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalElasticsearchChatDataSourceParameters(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.cs deleted file mode 100644 index eabb3792a631..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalElasticsearchChatDataSourceParameters.cs +++ /dev/null @@ -1,82 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalElasticsearchChatDataSourceParameters - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - public InternalElasticsearchChatDataSourceParameters(Uri endpoint, string indexName, DataSourceAuthentication authentication) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - - Endpoint = endpoint; - IndexName = indexName; - InternalIncludeContexts = new ChangeTrackingList(); - Authentication = authentication; - } - - internal InternalElasticsearchChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, Uri endpoint, string indexName, IList internalIncludeContexts, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceQueryType? queryType, DataSourceVectorizer vectorizationSource, IDictionary additionalBinaryDataProperties) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - Endpoint = endpoint; - IndexName = indexName; - InternalIncludeContexts = internalIncludeContexts; - Authentication = authentication; - FieldMappings = fieldMappings; - QueryType = queryType; - VectorizationSource = vectorizationSource; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - - /// Gets the Endpoint. - public Uri Endpoint { get; set; } - - /// Gets the IndexName. - public string IndexName { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.Serialization.cs deleted file mode 100644 index 4d9e4fb87e4f..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.Serialization.cs +++ /dev/null @@ -1,349 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalMongoDBChatDataSourceParameters : IJsonModel - { - internal InternalMongoDBChatDataSourceParameters() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalMongoDBChatDataSourceParameters)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(TopNDocuments) && _additionalBinaryDataProperties?.ContainsKey("top_n_documents") != true) - { - writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); - } - if (Optional.IsDefined(InScope) && _additionalBinaryDataProperties?.ContainsKey("in_scope") != true) - { - writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); - } - if (Optional.IsDefined(Strictness) && _additionalBinaryDataProperties?.ContainsKey("strictness") != true) - { - writer.WritePropertyName("strictness"u8); - writer.WriteNumberValue(Strictness.Value); - } - if (Optional.IsDefined(MaxSearchQueries) && _additionalBinaryDataProperties?.ContainsKey("max_search_queries") != true) - { - writer.WritePropertyName("max_search_queries"u8); - writer.WriteNumberValue(MaxSearchQueries.Value); - } - if (Optional.IsDefined(AllowPartialResult) && _additionalBinaryDataProperties?.ContainsKey("allow_partial_result") != true) - { - writer.WritePropertyName("allow_partial_result"u8); - writer.WriteBooleanValue(AllowPartialResult.Value); - } - if (_additionalBinaryDataProperties?.ContainsKey("endpoint") != true) - { - writer.WritePropertyName("endpoint"u8); - writer.WriteStringValue(Endpoint); - } - if (_additionalBinaryDataProperties?.ContainsKey("database_name") != true) - { - writer.WritePropertyName("database_name"u8); - writer.WriteStringValue(DatabaseName); - } - if (_additionalBinaryDataProperties?.ContainsKey("collection_name") != true) - { - writer.WritePropertyName("collection_name"u8); - writer.WriteStringValue(CollectionName); - } - if (_additionalBinaryDataProperties?.ContainsKey("app_name") != true) - { - writer.WritePropertyName("app_name"u8); - writer.WriteStringValue(AppName); - } - if (_additionalBinaryDataProperties?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (_additionalBinaryDataProperties?.ContainsKey("fields_mapping") != true) - { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("authentication") != true) - { - writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(EmbeddingDependency, options); - } - if (Optional.IsCollectionDefined(_internalIncludeContexts) && _additionalBinaryDataProperties?.ContainsKey("include_contexts") != true) - { - writer.WritePropertyName("include_contexts"u8); - writer.WriteStartArray(); - foreach (string item in _internalIncludeContexts) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalMongoDBChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalMongoDBChatDataSourceParameters JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalMongoDBChatDataSourceParameters)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalMongoDBChatDataSourceParameters(document.RootElement, options); - } - - internal static InternalMongoDBChatDataSourceParameters DeserializeInternalMongoDBChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? topNDocuments = default; - bool? inScope = default; - int? strictness = default; - int? maxSearchQueries = default; - bool? allowPartialResult = default; - string endpoint = default; - string databaseName = default; - string collectionName = default; - string appName = default; - string indexName = default; - DataSourceFieldMappings fieldMappings = default; - DataSourceAuthentication authentication = default; - DataSourceVectorizer embeddingDependency = default; - IList internalIncludeContexts = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("top_n_documents"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - topNDocuments = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("in_scope"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - inScope = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("strictness"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - strictness = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("max_search_queries"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - maxSearchQueries = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("allow_partial_result"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allowPartialResult = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("endpoint"u8)) - { - endpoint = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("database_name"u8)) - { - databaseName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("collection_name"u8)) - { - collectionName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("app_name"u8)) - { - appName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("index_name"u8)) - { - indexName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("fields_mapping"u8)) - { - fieldMappings = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(prop.Value, options); - continue; - } - if (prop.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(prop.Value, options); - continue; - } - if (prop.NameEquals("embedding_dependency"u8)) - { - embeddingDependency = DataSourceVectorizer.DeserializeDataSourceVectorizer(prop.Value, options); - continue; - } - if (prop.NameEquals("include_contexts"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - internalIncludeContexts = array; - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalMongoDBChatDataSourceParameters( - topNDocuments, - inScope, - strictness, - maxSearchQueries, - allowPartialResult, - endpoint, - databaseName, - collectionName, - appName, - indexName, - fieldMappings, - authentication, - embeddingDependency, - internalIncludeContexts, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalMongoDBChatDataSourceParameters)} does not support writing '{options.Format}' format."); - } - } - - InternalMongoDBChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalMongoDBChatDataSourceParameters PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalMongoDBChatDataSourceParameters(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalMongoDBChatDataSourceParameters)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalMongoDBChatDataSourceParameters internalMongoDBChatDataSourceParameters) - { - if (internalMongoDBChatDataSourceParameters == null) - { - return null; - } - return BinaryContent.Create(internalMongoDBChatDataSourceParameters, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalMongoDBChatDataSourceParameters(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalMongoDBChatDataSourceParameters(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.cs deleted file mode 100644 index cce8acc6e969..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalMongoDBChatDataSourceParameters.cs +++ /dev/null @@ -1,103 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalMongoDBChatDataSourceParameters - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - public InternalMongoDBChatDataSourceParameters(string endpoint, string databaseName, string collectionName, string appName, string indexName, DataSourceFieldMappings fieldMappings, DataSourceAuthentication authentication, DataSourceVectorizer embeddingDependency) - { - Argument.AssertNotNull(endpoint, nameof(endpoint)); - Argument.AssertNotNull(databaseName, nameof(databaseName)); - Argument.AssertNotNull(collectionName, nameof(collectionName)); - Argument.AssertNotNull(appName, nameof(appName)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(fieldMappings, nameof(fieldMappings)); - Argument.AssertNotNull(authentication, nameof(authentication)); - Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); - - Endpoint = endpoint; - DatabaseName = databaseName; - CollectionName = collectionName; - AppName = appName; - IndexName = indexName; - FieldMappings = fieldMappings; - Authentication = authentication; - EmbeddingDependency = embeddingDependency; - _internalIncludeContexts = new ChangeTrackingList(); - } - - internal InternalMongoDBChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, string endpoint, string databaseName, string collectionName, string appName, string indexName, DataSourceFieldMappings fieldMappings, DataSourceAuthentication authentication, DataSourceVectorizer embeddingDependency, IList internalIncludeContexts, IDictionary additionalBinaryDataProperties) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - Endpoint = endpoint; - DatabaseName = databaseName; - CollectionName = collectionName; - AppName = appName; - IndexName = indexName; - FieldMappings = fieldMappings; - Authentication = authentication; - EmbeddingDependency = embeddingDependency; - _internalIncludeContexts = internalIncludeContexts; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - - /// The name of the MongoDB cluster endpoint. - public string Endpoint { get; set; } - - /// The name of the MongoDB database. - public string DatabaseName { get; set; } - - /// The name of the MongoDB collection. - public string CollectionName { get; set; } - - /// The name of the MongoDB application. - public string AppName { get; set; } - - /// The name of the MongoDB index. - public string IndexName { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.Serialization.cs deleted file mode 100644 index aad24b245716..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.Serialization.cs +++ /dev/null @@ -1,313 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalPineconeChatDataSourceParameters : IJsonModel - { - internal InternalPineconeChatDataSourceParameters() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalPineconeChatDataSourceParameters)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(TopNDocuments) && _additionalBinaryDataProperties?.ContainsKey("top_n_documents") != true) - { - writer.WritePropertyName("top_n_documents"u8); - writer.WriteNumberValue(TopNDocuments.Value); - } - if (Optional.IsDefined(InScope) && _additionalBinaryDataProperties?.ContainsKey("in_scope") != true) - { - writer.WritePropertyName("in_scope"u8); - writer.WriteBooleanValue(InScope.Value); - } - if (Optional.IsDefined(Strictness) && _additionalBinaryDataProperties?.ContainsKey("strictness") != true) - { - writer.WritePropertyName("strictness"u8); - writer.WriteNumberValue(Strictness.Value); - } - if (Optional.IsDefined(MaxSearchQueries) && _additionalBinaryDataProperties?.ContainsKey("max_search_queries") != true) - { - writer.WritePropertyName("max_search_queries"u8); - writer.WriteNumberValue(MaxSearchQueries.Value); - } - if (Optional.IsDefined(AllowPartialResult) && _additionalBinaryDataProperties?.ContainsKey("allow_partial_result") != true) - { - writer.WritePropertyName("allow_partial_result"u8); - writer.WriteBooleanValue(AllowPartialResult.Value); - } - if (_additionalBinaryDataProperties?.ContainsKey("environment") != true) - { - writer.WritePropertyName("environment"u8); - writer.WriteStringValue(Environment); - } - if (_additionalBinaryDataProperties?.ContainsKey("index_name") != true) - { - writer.WritePropertyName("index_name"u8); - writer.WriteStringValue(IndexName); - } - if (_additionalBinaryDataProperties?.ContainsKey("authentication") != true) - { - writer.WritePropertyName("authentication"u8); - writer.WriteObjectValue(Authentication, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("fields_mapping") != true) - { - writer.WritePropertyName("fields_mapping"u8); - writer.WriteObjectValue(FieldMappings, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("embedding_dependency") != true) - { - writer.WritePropertyName("embedding_dependency"u8); - writer.WriteObjectValue(VectorizationSource, options); - } - if (Optional.IsCollectionDefined(_internalIncludeContexts) && _additionalBinaryDataProperties?.ContainsKey("include_contexts") != true) - { - writer.WritePropertyName("include_contexts"u8); - writer.WriteStartArray(); - foreach (string item in _internalIncludeContexts) - { - if (item == null) - { - writer.WriteNullValue(); - continue; - } - writer.WriteStringValue(item); - } - writer.WriteEndArray(); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - InternalPineconeChatDataSourceParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected virtual InternalPineconeChatDataSourceParameters JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(InternalPineconeChatDataSourceParameters)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeInternalPineconeChatDataSourceParameters(document.RootElement, options); - } - - internal static InternalPineconeChatDataSourceParameters DeserializeInternalPineconeChatDataSourceParameters(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? topNDocuments = default; - bool? inScope = default; - int? strictness = default; - int? maxSearchQueries = default; - bool? allowPartialResult = default; - string environment = default; - string indexName = default; - DataSourceAuthentication authentication = default; - DataSourceFieldMappings fieldMappings = default; - DataSourceVectorizer vectorizationSource = default; - IList internalIncludeContexts = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("top_n_documents"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - topNDocuments = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("in_scope"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - inScope = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("strictness"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - strictness = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("max_search_queries"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - maxSearchQueries = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("allow_partial_result"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - allowPartialResult = prop.Value.GetBoolean(); - continue; - } - if (prop.NameEquals("environment"u8)) - { - environment = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("index_name"u8)) - { - indexName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("authentication"u8)) - { - authentication = DataSourceAuthentication.DeserializeDataSourceAuthentication(prop.Value, options); - continue; - } - if (prop.NameEquals("fields_mapping"u8)) - { - fieldMappings = DataSourceFieldMappings.DeserializeDataSourceFieldMappings(prop.Value, options); - continue; - } - if (prop.NameEquals("embedding_dependency"u8)) - { - vectorizationSource = DataSourceVectorizer.DeserializeDataSourceVectorizer(prop.Value, options); - continue; - } - if (prop.NameEquals("include_contexts"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - List array = new List(); - foreach (var item in prop.Value.EnumerateArray()) - { - if (item.ValueKind == JsonValueKind.Null) - { - array.Add(null); - } - else - { - array.Add(item.GetString()); - } - } - internalIncludeContexts = array; - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalPineconeChatDataSourceParameters( - topNDocuments, - inScope, - strictness, - maxSearchQueries, - allowPartialResult, - environment, - indexName, - authentication, - fieldMappings, - vectorizationSource, - internalIncludeContexts, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(InternalPineconeChatDataSourceParameters)} does not support writing '{options.Format}' format."); - } - } - - InternalPineconeChatDataSourceParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected virtual InternalPineconeChatDataSourceParameters PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeInternalPineconeChatDataSourceParameters(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(InternalPineconeChatDataSourceParameters)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - public static implicit operator BinaryContent(InternalPineconeChatDataSourceParameters internalPineconeChatDataSourceParameters) - { - if (internalPineconeChatDataSourceParameters == null) - { - return null; - } - return BinaryContent.Create(internalPineconeChatDataSourceParameters, ModelSerializationExtensions.WireOptions); - } - - public static explicit operator InternalPineconeChatDataSourceParameters(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeInternalPineconeChatDataSourceParameters(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.cs deleted file mode 100644 index 89bc9527124c..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalPineconeChatDataSourceParameters.cs +++ /dev/null @@ -1,85 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalPineconeChatDataSourceParameters - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - public InternalPineconeChatDataSourceParameters(string environment, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceVectorizer vectorizationSource) - { - Argument.AssertNotNull(environment, nameof(environment)); - Argument.AssertNotNull(indexName, nameof(indexName)); - Argument.AssertNotNull(authentication, nameof(authentication)); - Argument.AssertNotNull(fieldMappings, nameof(fieldMappings)); - Argument.AssertNotNull(vectorizationSource, nameof(vectorizationSource)); - - Environment = environment; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - VectorizationSource = vectorizationSource; - _internalIncludeContexts = new ChangeTrackingList(); - } - - internal InternalPineconeChatDataSourceParameters(int? topNDocuments, bool? inScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, string environment, string indexName, DataSourceAuthentication authentication, DataSourceFieldMappings fieldMappings, DataSourceVectorizer vectorizationSource, IList internalIncludeContexts, IDictionary additionalBinaryDataProperties) - { - TopNDocuments = topNDocuments; - InScope = inScope; - Strictness = strictness; - MaxSearchQueries = maxSearchQueries; - AllowPartialResult = allowPartialResult; - Environment = environment; - IndexName = indexName; - Authentication = authentication; - FieldMappings = fieldMappings; - VectorizationSource = vectorizationSource; - _internalIncludeContexts = internalIncludeContexts; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// The configured number of documents to feature in the query. - public int? TopNDocuments { get; set; } - - /// Whether queries should be restricted to use of the indexed data. - public bool? InScope { get; set; } - - /// - /// The configured strictness of the search relevance filtering. - /// Higher strictness will increase precision but lower recall of the answer. - /// - public int? Strictness { get; set; } - - /// - /// The maximum number of rewritten queries that should be sent to the search provider for a single user message. - /// By default, the system will make an automatic determination. - /// - public int? MaxSearchQueries { get; set; } - - /// - /// If set to true, the system will allow partial search results to be used and the request will fail if all - /// partial queries fail. If not specified or specified as false, the request will fail if any search query fails. - /// - public bool? AllowPartialResult { get; set; } - - /// The environment name to use with Pinecone. - public string Environment { get; set; } - - /// The name of the Pinecone database index to use. - public string IndexName { get; set; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.Serialization.cs deleted file mode 100644 index a07d42685e6a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.Serialization.cs +++ /dev/null @@ -1,105 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSource : IJsonModel - { - internal InternalUnknownAzureChatDataSource() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatDataSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - } - - ChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected override ChatDataSource JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ChatDataSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeChatDataSource(document.RootElement, options); - } - - internal static InternalUnknownAzureChatDataSource DeserializeInternalUnknownAzureChatDataSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "unknown"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalUnknownAzureChatDataSource(@type, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - ChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected override ChatDataSource PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.cs deleted file mode 100644 index 4b8afdf9db48..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSource.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSource : ChatDataSource - { - internal InternalUnknownAzureChatDataSource(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) - { - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.Serialization.cs deleted file mode 100644 index 21aaab7d44c4..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.Serialization.cs +++ /dev/null @@ -1,105 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSourceAuthenticationOptions : IJsonModel - { - internal InternalUnknownAzureChatDataSourceAuthenticationOptions() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - } - - DataSourceAuthentication IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected override DataSourceAuthentication JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceAuthentication(document.RootElement, options); - } - - internal static InternalUnknownAzureChatDataSourceAuthenticationOptions DeserializeInternalUnknownAzureChatDataSourceAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "unknown"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalUnknownAzureChatDataSourceAuthenticationOptions(@type, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support writing '{options.Format}' format."); - } - } - - DataSourceAuthentication IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected override DataSourceAuthentication PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeDataSourceAuthentication(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceAuthentication)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.cs deleted file mode 100644 index fefb207091eb..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceAuthenticationOptions.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSourceAuthenticationOptions : DataSourceAuthentication - { - internal InternalUnknownAzureChatDataSourceAuthenticationOptions(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) - { - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.Serialization.cs deleted file mode 100644 index cb3a779a668a..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.Serialization.cs +++ /dev/null @@ -1,105 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSourceVectorizationSource : IJsonModel - { - internal InternalUnknownAzureChatDataSourceVectorizationSource() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - } - - DataSourceVectorizer IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - protected override DataSourceVectorizer JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeDataSourceVectorizer(document.RootElement, options); - } - - internal static InternalUnknownAzureChatDataSourceVectorizationSource DeserializeInternalUnknownAzureChatDataSourceVectorizationSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "unknown"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new InternalUnknownAzureChatDataSourceVectorizationSource(@type, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support writing '{options.Format}' format."); - } - } - - DataSourceVectorizer IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - protected override DataSourceVectorizer PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeDataSourceVectorizer(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(DataSourceVectorizer)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.cs deleted file mode 100644 index 2f85fedc78ae..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/InternalUnknownAzureChatDataSourceVectorizationSource.cs +++ /dev/null @@ -1,16 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI.Chat -{ - internal partial class InternalUnknownAzureChatDataSourceVectorizationSource : DataSourceVectorizer - { - internal InternalUnknownAzureChatDataSourceVectorizationSource(string @type, IDictionary additionalBinaryDataProperties) : base(@type ?? "unknown", additionalBinaryDataProperties) - { - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.Serialization.cs deleted file mode 100644 index 512211c9337e..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.Serialization.cs +++ /dev/null @@ -1,139 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class MongoDBChatDataSource : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(MongoDBChatDataSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - } - - MongoDBChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (MongoDBChatDataSource)JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected override ChatDataSource JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(MongoDBChatDataSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeMongoDBChatDataSource(document.RootElement, options); - } - - internal static MongoDBChatDataSource DeserializeMongoDBChatDataSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "mongo_db"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - InternalMongoDBChatDataSourceParameters internalParameters = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("parameters"u8)) - { - internalParameters = InternalMongoDBChatDataSourceParameters.DeserializeInternalMongoDBChatDataSourceParameters(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new MongoDBChatDataSource(@type, additionalBinaryDataProperties, internalParameters); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(MongoDBChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - MongoDBChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (MongoDBChatDataSource)PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected override ChatDataSource PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeMongoDBChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(MongoDBChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(MongoDBChatDataSource mongoDBChatDataSource) - { - if (mongoDBChatDataSource == null) - { - return null; - } - return BinaryContent.Create(mongoDBChatDataSource, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator MongoDBChatDataSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeMongoDBChatDataSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.cs deleted file mode 100644 index ff06412c62d9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/MongoDBChatDataSource.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Azure.AI.OpenAI.Chat -{ - /// The MongoDBChatDataSource. - public partial class MongoDBChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.Serialization.cs deleted file mode 100644 index 2b35a006eced..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.Serialization.cs +++ /dev/null @@ -1,139 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; -using Azure.AI.OpenAI; - -namespace Azure.AI.OpenAI.Chat -{ - /// - public partial class PineconeChatDataSource : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PineconeChatDataSource)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (_additionalBinaryDataProperties?.ContainsKey("parameters") != true) - { - writer.WritePropertyName("parameters"u8); - writer.WriteObjectValue(InternalParameters, options); - } - } - - PineconeChatDataSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (PineconeChatDataSource)JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected override ChatDataSource JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(PineconeChatDataSource)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializePineconeChatDataSource(document.RootElement, options); - } - - internal static PineconeChatDataSource DeserializePineconeChatDataSource(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string @type = "pinecone"; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - InternalPineconeChatDataSourceParameters internalParameters = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("type"u8)) - { - @type = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("parameters"u8)) - { - internalParameters = InternalPineconeChatDataSourceParameters.DeserializeInternalPineconeChatDataSourceParameters(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new PineconeChatDataSource(@type, additionalBinaryDataProperties, internalParameters); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(PineconeChatDataSource)} does not support writing '{options.Format}' format."); - } - } - - PineconeChatDataSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (PineconeChatDataSource)PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected override ChatDataSource PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializePineconeChatDataSource(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(PineconeChatDataSource)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(PineconeChatDataSource pineconeChatDataSource) - { - if (pineconeChatDataSource == null) - { - return null; - } - return BinaryContent.Create(pineconeChatDataSource, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator PineconeChatDataSource(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializePineconeChatDataSource(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.cs deleted file mode 100644 index ab9f57629fc1..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/PineconeChatDataSource.cs +++ /dev/null @@ -1,11 +0,0 @@ -// - -#nullable disable - -namespace Azure.AI.OpenAI.Chat -{ - /// The PineconeChatDataSource. - public partial class PineconeChatDataSource : ChatDataSource - { - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.Serialization.cs deleted file mode 100644 index 2cf7a7eaa814..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.Serialization.cs +++ /dev/null @@ -1,169 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class RequestContentFilterResult : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(RequestContentFilterResult)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(PromptIndex) && _additionalBinaryDataProperties?.ContainsKey("prompt_index") != true) - { - writer.WritePropertyName("prompt_index"u8); - writer.WriteNumberValue(PromptIndex.Value); - } - if (Optional.IsDefined(InternalResults) && _additionalBinaryDataProperties?.ContainsKey("content_filter_results") != true) - { - writer.WritePropertyName("content_filter_results"u8); - writer.WriteObjectValue(InternalResults, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - RequestContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual RequestContentFilterResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(RequestContentFilterResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRequestContentFilterResult(document.RootElement, options); - } - - internal static RequestContentFilterResult DeserializeRequestContentFilterResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - int? promptIndex = default; - InternalAzureContentFilterResultForPromptContentFilterResults internalResults = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("prompt_index"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - promptIndex = prop.Value.GetInt32(); - continue; - } - if (prop.NameEquals("content_filter_results"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - internalResults = InternalAzureContentFilterResultForPromptContentFilterResults.DeserializeInternalAzureContentFilterResultForPromptContentFilterResults(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new RequestContentFilterResult(promptIndex, internalResults, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(RequestContentFilterResult)} does not support writing '{options.Format}' format."); - } - } - - RequestContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual RequestContentFilterResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeRequestContentFilterResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(RequestContentFilterResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(RequestContentFilterResult requestContentFilterResult) - { - if (requestContentFilterResult == null) - { - return null; - } - return BinaryContent.Create(requestContentFilterResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator RequestContentFilterResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeRequestContentFilterResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.cs deleted file mode 100644 index b9a34dd78b05..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestContentFilterResult.cs +++ /dev/null @@ -1,34 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A content filter result associated with a single input prompt item into a generative AI system. - public partial class RequestContentFilterResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal RequestContentFilterResult() - { - } - - internal RequestContentFilterResult(int? promptIndex, InternalAzureContentFilterResultForPromptContentFilterResults internalResults, IDictionary additionalBinaryDataProperties) - { - PromptIndex = promptIndex; - InternalResults = internalResults; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.Serialization.cs deleted file mode 100644 index 844fd9b42b10..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.Serialization.cs +++ /dev/null @@ -1,214 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class RequestImageContentFilterResult : IJsonModel - { - internal RequestImageContentFilterResult() - { - } - - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(RequestImageContentFilterResult)} does not support writing '{format}' format."); - } - base.JsonModelWriteCore(writer, options); - if (Optional.IsDefined(Profanity) && _additionalBinaryDataProperties?.ContainsKey("profanity") != true) - { - writer.WritePropertyName("profanity"u8); - writer.WriteObjectValue(Profanity, options); - } - if (Optional.IsDefined(CustomBlocklists) && _additionalBinaryDataProperties?.ContainsKey("custom_blocklists") != true) - { - writer.WritePropertyName("custom_blocklists"u8); - writer.WriteObjectValue(CustomBlocklists, options); - } - if (_additionalBinaryDataProperties?.ContainsKey("jailbreak") != true) - { - writer.WritePropertyName("jailbreak"u8); - writer.WriteObjectValue(Jailbreak, options); - } - } - - RequestImageContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => (RequestImageContentFilterResult)JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected override ResponseImageContentFilterResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(RequestImageContentFilterResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRequestImageContentFilterResult(document.RootElement, options); - } - - internal static RequestImageContentFilterResult DeserializeRequestImageContentFilterResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult selfHarm = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - ContentFilterDetectionResult profanity = default; - ContentFilterBlocklistResult customBlocklists = default; - ContentFilterDetectionResult jailbreak = default; - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("sexual"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("violence"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("hate"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("self_harm"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("profanity"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(prop.Value, options); - continue; - } - if (prop.NameEquals("custom_blocklists"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - customBlocklists = ContentFilterBlocklistResult.DeserializeContentFilterBlocklistResult(prop.Value, options); - continue; - } - if (prop.NameEquals("jailbreak"u8)) - { - jailbreak = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new RequestImageContentFilterResult( - sexual, - violence, - hate, - selfHarm, - additionalBinaryDataProperties, - profanity, - customBlocklists, - jailbreak); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected override BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(RequestImageContentFilterResult)} does not support writing '{options.Format}' format."); - } - } - - RequestImageContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => (RequestImageContentFilterResult)PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected override ResponseImageContentFilterResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeRequestImageContentFilterResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(RequestImageContentFilterResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(RequestImageContentFilterResult requestImageContentFilterResult) - { - if (requestImageContentFilterResult == null) - { - return null; - } - return BinaryContent.Create(requestImageContentFilterResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator RequestImageContentFilterResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeRequestImageContentFilterResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.cs deleted file mode 100644 index 7fa092e11901..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/RequestImageContentFilterResult.cs +++ /dev/null @@ -1,41 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A content filter result for an image generation operation's input request content. - public partial class RequestImageContentFilterResult : ResponseImageContentFilterResult - { - internal RequestImageContentFilterResult(ContentFilterDetectionResult jailbreak) - { - Jailbreak = jailbreak; - } - - internal RequestImageContentFilterResult(ContentFilterSeverityResult sexual, ContentFilterSeverityResult violence, ContentFilterSeverityResult hate, ContentFilterSeverityResult selfHarm, IDictionary additionalBinaryDataProperties, ContentFilterDetectionResult profanity, ContentFilterBlocklistResult customBlocklists, ContentFilterDetectionResult jailbreak) : base(sexual, violence, hate, selfHarm, additionalBinaryDataProperties) - { - Profanity = profanity; - CustomBlocklists = customBlocklists; - Jailbreak = jailbreak; - } - - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - public ContentFilterDetectionResult Profanity { get; } - - /// A collection of binary filtering outcomes for configured custom blocklists. - public ContentFilterBlocklistResult CustomBlocklists { get; } - - /// - /// A detection result that describes user prompt injection attacks, where malicious users deliberately exploit - /// system vulnerabilities to elicit unauthorized behavior from the LLM. This could lead to inappropriate content - /// generation or violations of system-imposed restrictions. - /// - public ContentFilterDetectionResult Jailbreak { get; } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.Serialization.cs deleted file mode 100644 index 98ec0a09dd8b..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.Serialization.cs +++ /dev/null @@ -1,300 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ResponseContentFilterResult : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResponseContentFilterResult)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Sexual) && _additionalBinaryDataProperties?.ContainsKey("sexual") != true) - { - writer.WritePropertyName("sexual"u8); - writer.WriteObjectValue(Sexual, options); - } - if (Optional.IsDefined(Hate) && _additionalBinaryDataProperties?.ContainsKey("hate") != true) - { - writer.WritePropertyName("hate"u8); - writer.WriteObjectValue(Hate, options); - } - if (Optional.IsDefined(Violence) && _additionalBinaryDataProperties?.ContainsKey("violence") != true) - { - writer.WritePropertyName("violence"u8); - writer.WriteObjectValue(Violence, options); - } - if (Optional.IsDefined(SelfHarm) && _additionalBinaryDataProperties?.ContainsKey("self_harm") != true) - { - writer.WritePropertyName("self_harm"u8); - writer.WriteObjectValue(SelfHarm, options); - } - if (Optional.IsDefined(Profanity) && _additionalBinaryDataProperties?.ContainsKey("profanity") != true) - { - writer.WritePropertyName("profanity"u8); - writer.WriteObjectValue(Profanity, options); - } - if (Optional.IsDefined(CustomBlocklists) && _additionalBinaryDataProperties?.ContainsKey("custom_blocklists") != true) - { - writer.WritePropertyName("custom_blocklists"u8); - writer.WriteObjectValue(CustomBlocklists, options); - } - if (Optional.IsDefined(ProtectedMaterialText) && _additionalBinaryDataProperties?.ContainsKey("protected_material_text") != true) - { - writer.WritePropertyName("protected_material_text"u8); - writer.WriteObjectValue(ProtectedMaterialText, options); - } - if (Optional.IsDefined(ProtectedMaterialCode) && _additionalBinaryDataProperties?.ContainsKey("protected_material_code") != true) - { - writer.WritePropertyName("protected_material_code"u8); - writer.WriteObjectValue(ProtectedMaterialCode, options); - } - if (Optional.IsDefined(Error) && _additionalBinaryDataProperties?.ContainsKey("error") != true) - { - writer.WritePropertyName("error"u8); - writer.WriteObjectValue(Error, options); - } - if (Optional.IsDefined(UngroundedMaterial) && _additionalBinaryDataProperties?.ContainsKey("ungrounded_material") != true) - { - writer.WritePropertyName("ungrounded_material"u8); - writer.WriteObjectValue(UngroundedMaterial, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResponseContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ResponseContentFilterResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResponseContentFilterResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResponseContentFilterResult(document.RootElement, options); - } - - internal static ResponseContentFilterResult DeserializeResponseContentFilterResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult selfHarm = default; - ContentFilterDetectionResult profanity = default; - ContentFilterBlocklistResult customBlocklists = default; - ContentFilterDetectionResult protectedMaterialText = default; - ContentFilterProtectedMaterialResult protectedMaterialCode = default; - InternalAzureContentFilterResultForChoiceError error = default; - ContentFilterTextSpanResult ungroundedMaterial = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("sexual"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("hate"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("violence"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("self_harm"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("profanity"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - profanity = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(prop.Value, options); - continue; - } - if (prop.NameEquals("custom_blocklists"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - customBlocklists = ContentFilterBlocklistResult.DeserializeContentFilterBlocklistResult(prop.Value, options); - continue; - } - if (prop.NameEquals("protected_material_text"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - protectedMaterialText = ContentFilterDetectionResult.DeserializeContentFilterDetectionResult(prop.Value, options); - continue; - } - if (prop.NameEquals("protected_material_code"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - protectedMaterialCode = ContentFilterProtectedMaterialResult.DeserializeContentFilterProtectedMaterialResult(prop.Value, options); - continue; - } - if (prop.NameEquals("error"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - error = InternalAzureContentFilterResultForChoiceError.DeserializeInternalAzureContentFilterResultForChoiceError(prop.Value, options); - continue; - } - if (prop.NameEquals("ungrounded_material"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - ungroundedMaterial = ContentFilterTextSpanResult.DeserializeContentFilterTextSpanResult(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ResponseContentFilterResult( - sexual, - hate, - violence, - selfHarm, - profanity, - customBlocklists, - protectedMaterialText, - protectedMaterialCode, - error, - ungroundedMaterial, - additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ResponseContentFilterResult)} does not support writing '{options.Format}' format."); - } - } - - ResponseContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ResponseContentFilterResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeResponseContentFilterResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResponseContentFilterResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ResponseContentFilterResult responseContentFilterResult) - { - if (responseContentFilterResult == null) - { - return null; - } - return BinaryContent.Create(responseContentFilterResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ResponseContentFilterResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeResponseContentFilterResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.cs deleted file mode 100644 index 79bc8b01c414..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseContentFilterResult.cs +++ /dev/null @@ -1,85 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A content filter result for a single response item produced by a generative AI system. - public partial class ResponseContentFilterResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ResponseContentFilterResult() - { - } - - internal ResponseContentFilterResult(ContentFilterSeverityResult sexual, ContentFilterSeverityResult hate, ContentFilterSeverityResult violence, ContentFilterSeverityResult selfHarm, ContentFilterDetectionResult profanity, ContentFilterBlocklistResult customBlocklists, ContentFilterDetectionResult protectedMaterialText, ContentFilterProtectedMaterialResult protectedMaterialCode, InternalAzureContentFilterResultForChoiceError error, ContentFilterTextSpanResult ungroundedMaterial, IDictionary additionalBinaryDataProperties) - { - Sexual = sexual; - Hate = hate; - Violence = violence; - SelfHarm = selfHarm; - Profanity = profanity; - CustomBlocklists = customBlocklists; - ProtectedMaterialText = protectedMaterialText; - ProtectedMaterialCode = protectedMaterialCode; - Error = error; - UngroundedMaterial = ungroundedMaterial; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - public ContentFilterSeverityResult Sexual { get; } - - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on 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. - /// - public ContentFilterSeverityResult Hate { get; } - - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - public ContentFilterSeverityResult Violence { get; } - - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - public ContentFilterSeverityResult SelfHarm { get; } - - /// - /// A detection result that identifies whether crude, vulgar, or otherwise objection language is present in the - /// content. - /// - public ContentFilterDetectionResult Profanity { get; } - - /// A collection of binary filtering outcomes for configured custom blocklists. - public ContentFilterBlocklistResult CustomBlocklists { get; } - - /// A detection result that describes a match against text protected under copyright or other status. - public ContentFilterDetectionResult ProtectedMaterialText { get; } - - /// A detection result that describes a match against licensed code or other protected source material. - public ContentFilterProtectedMaterialResult ProtectedMaterialCode { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.Serialization.cs deleted file mode 100644 index 09de1cee2f23..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.Serialization.cs +++ /dev/null @@ -1,199 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class ResponseImageContentFilterResult : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResponseImageContentFilterResult)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(Sexual) && _additionalBinaryDataProperties?.ContainsKey("sexual") != true) - { - writer.WritePropertyName("sexual"u8); - writer.WriteObjectValue(Sexual, options); - } - if (Optional.IsDefined(Violence) && _additionalBinaryDataProperties?.ContainsKey("violence") != true) - { - writer.WritePropertyName("violence"u8); - writer.WriteObjectValue(Violence, options); - } - if (Optional.IsDefined(Hate) && _additionalBinaryDataProperties?.ContainsKey("hate") != true) - { - writer.WritePropertyName("hate"u8); - writer.WriteObjectValue(Hate, options); - } - if (Optional.IsDefined(SelfHarm) && _additionalBinaryDataProperties?.ContainsKey("self_harm") != true) - { - writer.WritePropertyName("self_harm"u8); - writer.WriteObjectValue(SelfHarm, options); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - ResponseImageContentFilterResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual ResponseImageContentFilterResult JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(ResponseImageContentFilterResult)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeResponseImageContentFilterResult(document.RootElement, options); - } - - internal static ResponseImageContentFilterResult DeserializeResponseImageContentFilterResult(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - ContentFilterSeverityResult sexual = default; - ContentFilterSeverityResult violence = default; - ContentFilterSeverityResult hate = default; - ContentFilterSeverityResult selfHarm = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("sexual"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - sexual = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("violence"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - violence = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("hate"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - hate = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (prop.NameEquals("self_harm"u8)) - { - if (prop.Value.ValueKind == JsonValueKind.Null) - { - continue; - } - selfHarm = ContentFilterSeverityResult.DeserializeContentFilterSeverityResult(prop.Value, options); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new ResponseImageContentFilterResult(sexual, violence, hate, selfHarm, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(ResponseImageContentFilterResult)} does not support writing '{options.Format}' format."); - } - } - - ResponseImageContentFilterResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual ResponseImageContentFilterResult PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeResponseImageContentFilterResult(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(ResponseImageContentFilterResult)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(ResponseImageContentFilterResult responseImageContentFilterResult) - { - if (responseImageContentFilterResult == null) - { - return null; - } - return BinaryContent.Create(responseImageContentFilterResult, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator ResponseImageContentFilterResult(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeResponseImageContentFilterResult(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.cs deleted file mode 100644 index f60b7bf911a9..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/ResponseImageContentFilterResult.cs +++ /dev/null @@ -1,64 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// A content filter result for an image generation operation's output response content. - public partial class ResponseImageContentFilterResult - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal ResponseImageContentFilterResult() - { - } - - internal ResponseImageContentFilterResult(ContentFilterSeverityResult sexual, ContentFilterSeverityResult violence, ContentFilterSeverityResult hate, ContentFilterSeverityResult selfHarm, IDictionary additionalBinaryDataProperties) - { - Sexual = sexual; - Violence = violence; - Hate = hate; - SelfHarm = selfHarm; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// - /// A content filter category for language related to anatomical organs and genitals, romantic relationships, acts - /// portrayed in erotic or affectionate terms, pregnancy, physical sexual acts, including those portrayed as an - /// assault or a forced sexual violent act against one's will, prostitution, pornography, and abuse. - /// - public ContentFilterSeverityResult Sexual { get; } - - /// - /// A content filter category for language related to physical actions intended to hurt, injure, damage, or kill - /// someone or something; describes weapons, guns and related entities, such as manufactures, associations, - /// legislation, and so on. - /// - public ContentFilterSeverityResult Violence { get; } - - /// - /// A content filter category that can refer to any content that attacks or uses pejorative or discriminatory - /// language with reference to a person or identity group based on 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. - /// - public ContentFilterSeverityResult Hate { get; } - - /// - /// A content filter category that describes language related to physical actions intended to purposely hurt, injure, - /// damage one's body or kill oneself. - /// - public ContentFilterSeverityResult SelfHarm { get; } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.Serialization.cs deleted file mode 100644 index b0aacd3bc4d1..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.Serialization.cs +++ /dev/null @@ -1,183 +0,0 @@ -// - -#nullable disable - -using System; -using System.ClientModel; -using System.ClientModel.Primitives; -using System.Collections.Generic; -using System.Text.Json; - -namespace Azure.AI.OpenAI -{ - /// - public partial class UserSecurityContext : IJsonModel - { - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - writer.WriteStartObject(); - JsonModelWriteCore(writer, options); - writer.WriteEndObject(); - } - - /// The JSON writer. - /// The client options for reading and writing models. - protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(UserSecurityContext)} does not support writing '{format}' format."); - } - if (Optional.IsDefined(ApplicationName) && _additionalBinaryDataProperties?.ContainsKey("application_name") != true) - { - writer.WritePropertyName("application_name"u8); - writer.WriteStringValue(ApplicationName); - } - if (Optional.IsDefined(EndUserId) && _additionalBinaryDataProperties?.ContainsKey("end_user_id") != true) - { - writer.WritePropertyName("end_user_id"u8); - writer.WriteStringValue(EndUserId); - } - if (Optional.IsDefined(EndUserTenantId) && _additionalBinaryDataProperties?.ContainsKey("end_user_tenant_id") != true) - { - writer.WritePropertyName("end_user_tenant_id"u8); - writer.WriteStringValue(EndUserTenantId); - } - if (Optional.IsDefined(SourceIP) && _additionalBinaryDataProperties?.ContainsKey("source_ip") != true) - { - writer.WritePropertyName("source_ip"u8); - writer.WriteStringValue(SourceIP); - } - if (options.Format != "W" && _additionalBinaryDataProperties != null) - { - foreach (var item in _additionalBinaryDataProperties) - { - if (ModelSerializationExtensions.IsSentinelValue(item.Value)) - { - continue; - } - writer.WritePropertyName(item.Key); -#if NET6_0_OR_GREATER - writer.WriteRawValue(item.Value); -#else - using (JsonDocument document = JsonDocument.Parse(item.Value)) - { - JsonSerializer.Serialize(writer, document.RootElement); - } -#endif - } - } - } - - UserSecurityContext IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options); - - /// The JSON reader. - /// The client options for reading and writing models. - protected virtual UserSecurityContext JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - if (format != "J") - { - throw new FormatException($"The model {nameof(UserSecurityContext)} does not support reading '{format}' format."); - } - using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeUserSecurityContext(document.RootElement, options); - } - - internal static UserSecurityContext DeserializeUserSecurityContext(JsonElement element, ModelReaderWriterOptions options) - { - if (element.ValueKind == JsonValueKind.Null) - { - return null; - } - string applicationName = default; - string endUserId = default; - string endUserTenantId = default; - string sourceIP = default; - IDictionary additionalBinaryDataProperties = new ChangeTrackingDictionary(); - foreach (var prop in element.EnumerateObject()) - { - if (prop.NameEquals("application_name"u8)) - { - applicationName = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("end_user_id"u8)) - { - endUserId = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("end_user_tenant_id"u8)) - { - endUserTenantId = prop.Value.GetString(); - continue; - } - if (prop.NameEquals("source_ip"u8)) - { - sourceIP = prop.Value.GetString(); - continue; - } - if (options.Format != "W") - { - additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText())); - } - } - return new UserSecurityContext(applicationName, endUserId, endUserTenantId, sourceIP, additionalBinaryDataProperties); - } - - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options); - - /// The client options for reading and writing models. - protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - return ModelReaderWriter.Write(this, options); - default: - throw new FormatException($"The model {nameof(UserSecurityContext)} does not support writing '{options.Format}' format."); - } - } - - UserSecurityContext IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options); - - /// The data to parse. - /// The client options for reading and writing models. - protected virtual UserSecurityContext PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options) - { - string format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; - switch (format) - { - case "J": - using (JsonDocument document = JsonDocument.Parse(data)) - { - return DeserializeUserSecurityContext(document.RootElement, options); - } - default: - throw new FormatException($"The model {nameof(UserSecurityContext)} does not support reading '{options.Format}' format."); - } - } - - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; - - /// The to serialize into . - public static implicit operator BinaryContent(UserSecurityContext userSecurityContext) - { - if (userSecurityContext == null) - { - return null; - } - return BinaryContent.Create(userSecurityContext, ModelSerializationExtensions.WireOptions); - } - - /// The to deserialize the from. - public static explicit operator UserSecurityContext(ClientResult result) - { - using PipelineResponse response = result.GetRawResponse(); - using JsonDocument document = JsonDocument.Parse(response.Content); - return DeserializeUserSecurityContext(document.RootElement, ModelSerializationExtensions.WireOptions); - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.cs deleted file mode 100644 index 20cfafcfbbfa..000000000000 --- a/sdk/openai/Azure.AI.OpenAI/src/Generated/Models/UserSecurityContext.cs +++ /dev/null @@ -1,32 +0,0 @@ -// - -#nullable disable - -using System; -using System.Collections.Generic; - -namespace Azure.AI.OpenAI -{ - /// User security context contains several parameters that describe the application itself, and the end user that interacts with the application. These fields assist your security operations teams to investigate and mitigate security incidents by providing a comprehensive approach to protecting your AI applications. [Learn more](https://aka.ms/TP4AI/Documentation/EndUserContext) about protecting AI applications using Microsoft Defender for Cloud. - public partial class UserSecurityContext - { - /// Keeps track of any properties unknown to the library. - private protected IDictionary _additionalBinaryDataProperties; - - internal UserSecurityContext(string applicationName, string endUserId, string endUserTenantId, string sourceIP, IDictionary additionalBinaryDataProperties) - { - ApplicationName = applicationName; - EndUserId = endUserId; - EndUserTenantId = endUserTenantId; - SourceIP = sourceIP; - _additionalBinaryDataProperties = additionalBinaryDataProperties; - } - - /// - internal IDictionary SerializedAdditionalRawData - { - get => _additionalBinaryDataProperties; - set => _additionalBinaryDataProperties = value; - } - } -} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..3b9d34d2026e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class MongoDBChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MongoDBChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + } + + MongoDBChatExtensionConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MongoDBChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMongoDBChatExtensionConfiguration(document.RootElement, options); + } + + internal static MongoDBChatExtensionConfiguration DeserializeMongoDBChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + MongoDBChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = MongoDBChatExtensionParameters.DeserializeMongoDBChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MongoDBChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + MongoDBChatExtensionConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMongoDBChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new MongoDBChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMongoDBChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.cs new file mode 100644 index 000000000000..d83d67452853 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionConfiguration.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A specific representation of configurable options for a MongoDB chat extension configuration. + public partial class MongoDBChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters for the MongoDB chat extension. + /// is null. + public MongoDBChatExtensionConfiguration(MongoDBChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.MongoDB; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters for the MongoDB chat extension. + internal MongoDBChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, MongoDBChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal MongoDBChatExtensionConfiguration() + { + } + + /// The parameters for the MongoDB chat extension. + public MongoDBChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.Serialization.cs new file mode 100644 index 000000000000..27b498eb5ad6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.Serialization.cs @@ -0,0 +1,327 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class MongoDBChatExtensionParameters : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(DocumentCount)) + { + writer.WritePropertyName("top_n_documents"u8); + writer.WriteNumberValue(DocumentCount.Value); + } + if (Optional.IsDefined(ShouldRestrictResultScope)) + { + writer.WritePropertyName("in_scope"u8); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); + } + if (Optional.IsDefined(Strictness)) + { + writer.WritePropertyName("strictness"u8); + writer.WriteNumberValue(Strictness.Value); + } + if (Optional.IsDefined(MaxSearchQueries)) + { + writer.WritePropertyName("max_search_queries"u8); + writer.WriteNumberValue(MaxSearchQueries.Value); + } + if (Optional.IsDefined(AllowPartialResult)) + { + writer.WritePropertyName("allow_partial_result"u8); + writer.WriteBooleanValue(AllowPartialResult.Value); + } + if (Optional.IsCollectionDefined(IncludeContexts)) + { + writer.WritePropertyName("include_contexts"u8); + writer.WriteStartArray(); + foreach (var item in IncludeContexts) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Authentication)) + { + writer.WritePropertyName("authentication"u8); + writer.WriteObjectValue(Authentication, options); + } + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint); + writer.WritePropertyName("collection_name"u8); + writer.WriteStringValue(CollectionName); + writer.WritePropertyName("database_name"u8); + writer.WriteStringValue(DatabaseName); + writer.WritePropertyName("app_name"u8); + writer.WriteStringValue(AppName); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldsMapping, options); + writer.WritePropertyName("embedding_dependency"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(EmbeddingDependency); +#else + using (JsonDocument document = JsonDocument.Parse(EmbeddingDependency, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MongoDBChatExtensionParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMongoDBChatExtensionParameters(document.RootElement, options); + } + + internal static MongoDBChatExtensionParameters DeserializeMongoDBChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? topNDocuments = default; + bool? inScope = default; + int? strictness = default; + int? maxSearchQueries = default; + bool? allowPartialResult = default; + IList includeContexts = default; + OnYourDataUsernameAndPasswordAuthenticationOptions authentication = default; + string endpoint = default; + string collectionName = default; + string databaseName = default; + string appName = default; + string indexName = default; + MongoDBChatExtensionParametersFieldsMapping fieldsMapping = default; + BinaryData embeddingDependency = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("top_n_documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topNDocuments = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("in_scope"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inScope = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("strictness"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + strictness = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_search_queries"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxSearchQueries = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("allow_partial_result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + allowPartialResult = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("include_contexts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new OnYourDataContextProperty(item.GetString())); + } + includeContexts = array; + continue; + } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataUsernameAndPasswordAuthenticationOptions.DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(property.Value, options); + continue; + } + if (property.NameEquals("endpoint"u8)) + { + endpoint = property.Value.GetString(); + continue; + } + if (property.NameEquals("collection_name"u8)) + { + collectionName = property.Value.GetString(); + continue; + } + if (property.NameEquals("database_name"u8)) + { + databaseName = property.Value.GetString(); + continue; + } + if (property.NameEquals("app_name"u8)) + { + appName = property.Value.GetString(); + continue; + } + if (property.NameEquals("index_name"u8)) + { + indexName = property.Value.GetString(); + continue; + } + if (property.NameEquals("fields_mapping"u8)) + { + fieldsMapping = MongoDBChatExtensionParametersFieldsMapping.DeserializeMongoDBChatExtensionParametersFieldsMapping(property.Value, options); + continue; + } + if (property.NameEquals("embedding_dependency"u8)) + { + embeddingDependency = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MongoDBChatExtensionParameters( + topNDocuments, + inScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts ?? new ChangeTrackingList(), + authentication, + endpoint, + collectionName, + databaseName, + appName, + indexName, + fieldsMapping, + embeddingDependency, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support writing '{options.Format}' format."); + } + } + + MongoDBChatExtensionParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMongoDBChatExtensionParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MongoDBChatExtensionParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMongoDBChatExtensionParameters(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.cs new file mode 100644 index 000000000000..2bcbfbd262e3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParameters.cs @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters for the MongoDB chat extension. The supported authentication types are AccessToken, SystemAssignedManagedIdentity and UserAssignedManagedIdentity. + public partial class MongoDBChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The endpoint name for MongoDB. + /// The collection name for MongoDB. + /// The database name for MongoDB. + /// The app name for MongoDB. + /// The name of the MongoDB index. + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + /// The vectorization source to use with the MongoDB chat extension. + /// , , , , , or is null. + public MongoDBChatExtensionParameters(string endpoint, string collectionName, string databaseName, string appName, string indexName, MongoDBChatExtensionParametersFieldsMapping fieldsMapping, BinaryData embeddingDependency) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(collectionName, nameof(collectionName)); + Argument.AssertNotNull(databaseName, nameof(databaseName)); + Argument.AssertNotNull(appName, nameof(appName)); + Argument.AssertNotNull(indexName, nameof(indexName)); + Argument.AssertNotNull(fieldsMapping, nameof(fieldsMapping)); + Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); + + IncludeContexts = new ChangeTrackingList(); + Endpoint = endpoint; + CollectionName = collectionName; + DatabaseName = databaseName; + AppName = appName; + IndexName = indexName; + FieldsMapping = fieldsMapping; + EmbeddingDependency = embeddingDependency; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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 endpoint name for MongoDB. + /// The collection name for MongoDB. + /// The database name for MongoDB. + /// The app name for MongoDB. + /// The name of the MongoDB index. + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + /// The vectorization source to use with the MongoDB chat extension. + /// Keeps track of any properties unknown to the library. + internal MongoDBChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataUsernameAndPasswordAuthenticationOptions authentication, string endpoint, string collectionName, string databaseName, string appName, string indexName, MongoDBChatExtensionParametersFieldsMapping fieldsMapping, BinaryData embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + Endpoint = endpoint; + CollectionName = collectionName; + DatabaseName = databaseName; + AppName = appName; + IndexName = indexName; + FieldsMapping = fieldsMapping; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MongoDBChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// 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. + /// + public OnYourDataUsernameAndPasswordAuthenticationOptions Authentication { get; set; } + /// The endpoint name for MongoDB. + public string Endpoint { get; } + /// The collection name for MongoDB. + public string CollectionName { get; } + /// The database name for MongoDB. + public string DatabaseName { get; } + /// The app name for MongoDB. + public string AppName { get; } + /// The name of the MongoDB index. + public string IndexName { get; } + /// + /// Field mappings to apply to data used by the MongoDB data source. + /// Note that content and vector field mappings are required for MongoDB. + /// + public MongoDBChatExtensionParametersFieldsMapping FieldsMapping { get; } + /// + /// The vectorization source to use with the MongoDB chat extension. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData EmbeddingDependency { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.Serialization.cs new file mode 100644 index 000000000000..e9ee5bf74ed4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.Serialization.cs @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class MongoDBChatExtensionParametersFieldsMapping : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MongoDBChatExtensionParametersFieldsMapping)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFields) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + writer.WritePropertyName("vector_fields"u8); + writer.WriteStartArray(); + foreach (var item in VectorFields) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(TitleField)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleField); + } + if (Optional.IsDefined(UrlField)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlField); + } + if (Optional.IsDefined(FilepathField)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathField); + } + if (Optional.IsDefined(ContentFieldsSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldsSeparator); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + MongoDBChatExtensionParametersFieldsMapping IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(MongoDBChatExtensionParametersFieldsMapping)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeMongoDBChatExtensionParametersFieldsMapping(document.RootElement, options); + } + + internal static MongoDBChatExtensionParametersFieldsMapping DeserializeMongoDBChatExtensionParametersFieldsMapping(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + IList contentFields = default; + IList vectorFields = default; + string titleField = default; + string urlField = default; + string filepathField = default; + string contentFieldsSeparator = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("content_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("vector_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + vectorFields = array; + continue; + } + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new MongoDBChatExtensionParametersFieldsMapping( + contentFields, + vectorFields, + titleField, + urlField, + filepathField, + contentFieldsSeparator, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionParametersFieldsMapping)} does not support writing '{options.Format}' format."); + } + } + + MongoDBChatExtensionParametersFieldsMapping IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMongoDBChatExtensionParametersFieldsMapping(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(MongoDBChatExtensionParametersFieldsMapping)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static MongoDBChatExtensionParametersFieldsMapping FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeMongoDBChatExtensionParametersFieldsMapping(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.cs new file mode 100644 index 000000000000..bfe79488c08c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/MongoDBChatExtensionParametersFieldsMapping.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// The MongoDBChatExtensionParametersFieldsMapping. + public partial class MongoDBChatExtensionParametersFieldsMapping + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// + /// or is null. + public MongoDBChatExtensionParametersFieldsMapping(IEnumerable contentFields, IEnumerable vectorFields) + { + Argument.AssertNotNull(contentFields, nameof(contentFields)); + Argument.AssertNotNull(vectorFields, nameof(vectorFields)); + + ContentFields = contentFields.ToList(); + VectorFields = vectorFields.ToList(); + } + + /// Initializes a new instance of . + /// + /// + /// + /// + /// + /// + /// Keeps track of any properties unknown to the library. + internal MongoDBChatExtensionParametersFieldsMapping(IList contentFields, IList vectorFields, string titleField, string urlField, string filepathField, string contentFieldsSeparator, IDictionary serializedAdditionalRawData) + { + ContentFields = contentFields; + VectorFields = vectorFields; + TitleField = titleField; + UrlField = urlField; + FilepathField = filepathField; + ContentFieldsSeparator = contentFieldsSeparator; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal MongoDBChatExtensionParametersFieldsMapping() + { + } + + /// Gets the content fields. + public IList ContentFields { get; } + /// Gets the vector fields. + public IList VectorFields { get; } + /// Gets or sets the title field. + public string TitleField { get; set; } + /// Gets or sets the url field. + public string UrlField { get; set; } + /// Gets or sets the filepath field. + public string FilepathField { get; set; } + /// Gets or sets the content fields separator. + public string ContentFieldsSeparator { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..6d228e10f65f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataAccessTokenAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataAccessTokenAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("access_token"u8); + writer.WriteStringValue(AccessToken); + } + + OnYourDataAccessTokenAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataAccessTokenAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataAccessTokenAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataAccessTokenAuthenticationOptions DeserializeOnYourDataAccessTokenAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string accessToken = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("access_token"u8)) + { + accessToken = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataAccessTokenAuthenticationOptions(type, serializedAdditionalRawData, accessToken); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataAccessTokenAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataAccessTokenAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataAccessTokenAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataAccessTokenAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataAccessTokenAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataAccessTokenAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.cs new file mode 100644 index 000000000000..50ccaddc9fd2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAccessTokenAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using access token. + public partial class OnYourDataAccessTokenAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The access token to use for authentication. + /// is null. + public OnYourDataAccessTokenAuthenticationOptions(string accessToken) + { + Argument.AssertNotNull(accessToken, nameof(accessToken)); + + Type = OnYourDataAuthenticationType.AccessToken; + AccessToken = accessToken; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The access token to use for authentication. + internal OnYourDataAccessTokenAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string accessToken) : base(type, serializedAdditionalRawData) + { + AccessToken = accessToken; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataAccessTokenAuthenticationOptions() + { + } + + /// The access token to use for authentication. + public string AccessToken { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..33cf2dd711fa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataApiKeyAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataApiKeyAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + } + + OnYourDataApiKeyAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataApiKeyAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataApiKeyAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataApiKeyAuthenticationOptions DeserializeOnYourDataApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataApiKeyAuthenticationOptions(type, serializedAdditionalRawData, key); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataApiKeyAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataApiKeyAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataApiKeyAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataApiKeyAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.cs new file mode 100644 index 000000000000..f0a14f528a7c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataApiKeyAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an API key. + public partial class OnYourDataApiKeyAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The API key to use for authentication. + /// is null. + public OnYourDataApiKeyAuthenticationOptions(string key) + { + Argument.AssertNotNull(key, nameof(key)); + + Type = OnYourDataAuthenticationType.ApiKey; + Key = key; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The API key to use for authentication. + internal OnYourDataApiKeyAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string key) : base(type, serializedAdditionalRawData) + { + Key = key; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataApiKeyAuthenticationOptions() + { + } + + /// The API key to use for authentication. + public string Key { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..8e47fb638239 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.Serialization.cs @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownOnYourDataAuthenticationOptions))] + public partial class OnYourDataAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OnYourDataAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataAuthenticationOptions DeserializeOnYourDataAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "access_token": return OnYourDataAccessTokenAuthenticationOptions.DeserializeOnYourDataAccessTokenAuthenticationOptions(element, options); + case "api_key": return OnYourDataApiKeyAuthenticationOptions.DeserializeOnYourDataApiKeyAuthenticationOptions(element, options); + case "connection_string": return OnYourDataConnectionStringAuthenticationOptions.DeserializeOnYourDataConnectionStringAuthenticationOptions(element, options); + case "encoded_api_key": return OnYourDataEncodedApiKeyAuthenticationOptions.DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(element, options); + case "key_and_key_id": return OnYourDataKeyAndKeyIdAuthenticationOptions.DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(element, options); + case "system_assigned_managed_identity": return OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(element, options); + case "user_assigned_managed_identity": return OnYourDataUserAssignedManagedIdentityAuthenticationOptions.DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(element, options); + case "username_and_password": return OnYourDataUsernameAndPasswordAuthenticationOptions.DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(element, options); + } + } + return UnknownOnYourDataAuthenticationOptions.DeserializeUnknownOnYourDataAuthenticationOptions(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OnYourDataAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.cs new file mode 100644 index 000000000000..e507e2c7c801 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationOptions.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The authentication options for Azure OpenAI On Your Data. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public abstract partial class OnYourDataAuthenticationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected OnYourDataAuthenticationOptions() + { + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + internal OnYourDataAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The authentication type. + internal OnYourDataAuthenticationType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationType.cs new file mode 100644 index 000000000000..3505399d9f9d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataAuthenticationType.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The authentication types supported with Azure OpenAI On Your Data. + internal readonly partial struct OnYourDataAuthenticationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataAuthenticationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ApiKeyValue = "api_key"; + private const string ConnectionStringValue = "connection_string"; + private const string KeyAndKeyIdValue = "key_and_key_id"; + private const string EncodedApiKeyValue = "encoded_api_key"; + private const string AccessTokenValue = "access_token"; + private const string SystemAssignedManagedIdentityValue = "system_assigned_managed_identity"; + private const string UserAssignedManagedIdentityValue = "user_assigned_managed_identity"; + private const string UsernameAndPasswordValue = "username_and_password"; + + /// Authentication via API key. + public static OnYourDataAuthenticationType ApiKey { get; } = new OnYourDataAuthenticationType(ApiKeyValue); + /// Authentication via connection string. + public static OnYourDataAuthenticationType ConnectionString { get; } = new OnYourDataAuthenticationType(ConnectionStringValue); + /// Authentication via key and key ID pair. + public static OnYourDataAuthenticationType KeyAndKeyId { get; } = new OnYourDataAuthenticationType(KeyAndKeyIdValue); + /// Authentication via encoded API key. + public static OnYourDataAuthenticationType EncodedApiKey { get; } = new OnYourDataAuthenticationType(EncodedApiKeyValue); + /// Authentication via access token. + public static OnYourDataAuthenticationType AccessToken { get; } = new OnYourDataAuthenticationType(AccessTokenValue); + /// Authentication via system-assigned managed identity. + public static OnYourDataAuthenticationType SystemAssignedManagedIdentity { get; } = new OnYourDataAuthenticationType(SystemAssignedManagedIdentityValue); + /// Authentication via user-assigned managed identity. + public static OnYourDataAuthenticationType UserAssignedManagedIdentity { get; } = new OnYourDataAuthenticationType(UserAssignedManagedIdentityValue); + /// Authentication via username and password. + public static OnYourDataAuthenticationType UsernameAndPassword { get; } = new OnYourDataAuthenticationType(UsernameAndPasswordValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataAuthenticationType left, OnYourDataAuthenticationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataAuthenticationType left, OnYourDataAuthenticationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataAuthenticationType(string value) => new OnYourDataAuthenticationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataAuthenticationType other && Equals(other); + /// + public bool Equals(OnYourDataAuthenticationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..2a0e90537caa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataConnectionStringAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataConnectionStringAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("connection_string"u8); + writer.WriteStringValue(ConnectionString); + } + + OnYourDataConnectionStringAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataConnectionStringAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataConnectionStringAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataConnectionStringAuthenticationOptions DeserializeOnYourDataConnectionStringAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string connectionString = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("connection_string"u8)) + { + connectionString = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataConnectionStringAuthenticationOptions(type, serializedAdditionalRawData, connectionString); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataConnectionStringAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataConnectionStringAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataConnectionStringAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataConnectionStringAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataConnectionStringAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataConnectionStringAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.cs new file mode 100644 index 000000000000..a3a007891075 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataConnectionStringAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a connection string. + public partial class OnYourDataConnectionStringAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The connection string to use for authentication. + /// is null. + public OnYourDataConnectionStringAuthenticationOptions(string connectionString) + { + Argument.AssertNotNull(connectionString, nameof(connectionString)); + + Type = OnYourDataAuthenticationType.ConnectionString; + ConnectionString = connectionString; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The connection string to use for authentication. + internal OnYourDataConnectionStringAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string connectionString) : base(type, serializedAdditionalRawData) + { + ConnectionString = connectionString; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataConnectionStringAuthenticationOptions() + { + } + + /// The connection string to use for authentication. + public string ConnectionString { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataContextProperty.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataContextProperty.cs new file mode 100644 index 000000000000..741585547c4a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataContextProperty.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The context property. + public readonly partial struct OnYourDataContextProperty : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataContextProperty(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string CitationsValue = "citations"; + private const string IntentValue = "intent"; + private const string AllRetrievedDocumentsValue = "all_retrieved_documents"; + + /// The `citations` property. + public static OnYourDataContextProperty Citations { get; } = new OnYourDataContextProperty(CitationsValue); + /// The `intent` property. + public static OnYourDataContextProperty Intent { get; } = new OnYourDataContextProperty(IntentValue); + /// The `all_retrieved_documents` property. + public static OnYourDataContextProperty AllRetrievedDocuments { get; } = new OnYourDataContextProperty(AllRetrievedDocumentsValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataContextProperty left, OnYourDataContextProperty right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataContextProperty left, OnYourDataContextProperty right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataContextProperty(string value) => new OnYourDataContextProperty(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataContextProperty other && Equals(other); + /// + public bool Equals(OnYourDataContextProperty other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..7d91cc804bc7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataDeploymentNameVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataDeploymentNameVectorizationSource)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("deployment_name"u8); + writer.WriteStringValue(DeploymentName); + if (Optional.IsDefined(Dimensions)) + { + writer.WritePropertyName("dimensions"u8); + writer.WriteNumberValue(Dimensions.Value); + } + } + + OnYourDataDeploymentNameVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataDeploymentNameVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataDeploymentNameVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataDeploymentNameVectorizationSource DeserializeOnYourDataDeploymentNameVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string deploymentName = default; + int? dimensions = default; + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("deployment_name"u8)) + { + deploymentName = property.Value.GetString(); + continue; + } + if (property.NameEquals("dimensions"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + dimensions = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataDeploymentNameVectorizationSource(type, serializedAdditionalRawData, deploymentName, dimensions); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataDeploymentNameVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataDeploymentNameVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataDeploymentNameVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataDeploymentNameVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataDeploymentNameVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataDeploymentNameVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.cs new file mode 100644 index 000000000000..1183ff66cbe4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataDeploymentNameVectorizationSource.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class OnYourDataDeploymentNameVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// 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. + /// is null. + public OnYourDataDeploymentNameVectorizationSource(string deploymentName) + { + Argument.AssertNotNull(deploymentName, nameof(deploymentName)); + + Type = OnYourDataVectorizationSourceType.DeploymentName; + DeploymentName = deploymentName; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + /// 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. + /// The number of dimensions the embeddings should have. Only supported in `text-embedding-3` and later models. + internal OnYourDataDeploymentNameVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData, string deploymentName, int? dimensions) : base(type, serializedAdditionalRawData) + { + DeploymentName = deploymentName; + Dimensions = dimensions; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataDeploymentNameVectorizationSource() + { + } + + /// 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. + public string DeploymentName { get; } + /// The number of dimensions the embeddings should have. Only supported in `text-embedding-3` and later models. + public int? Dimensions { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..450665682eec --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataEncodedApiKeyAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("encoded_api_key"u8); + writer.WriteStringValue(EncodedApiKey); + } + + OnYourDataEncodedApiKeyAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataEncodedApiKeyAuthenticationOptions DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string encodedApiKey = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("encoded_api_key"u8)) + { + encodedApiKey = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataEncodedApiKeyAuthenticationOptions(type, serializedAdditionalRawData, encodedApiKey); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataEncodedApiKeyAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataEncodedApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataEncodedApiKeyAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataEncodedApiKeyAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.cs new file mode 100644 index 000000000000..927e2e27e169 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEncodedApiKeyAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an Elasticsearch encoded API key. + public partial class OnYourDataEncodedApiKeyAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The encoded API key to use for authentication. + /// is null. + public OnYourDataEncodedApiKeyAuthenticationOptions(string encodedApiKey) + { + Argument.AssertNotNull(encodedApiKey, nameof(encodedApiKey)); + + Type = OnYourDataAuthenticationType.EncodedApiKey; + EncodedApiKey = encodedApiKey; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The encoded API key to use for authentication. + internal OnYourDataEncodedApiKeyAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string encodedApiKey) : base(type, serializedAdditionalRawData) + { + EncodedApiKey = encodedApiKey; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataEncodedApiKeyAuthenticationOptions() + { + } + + /// The encoded API key to use for authentication. + public string EncodedApiKey { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..d182f3c2ce8c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataEndpointVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataEndpointVectorizationSource)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("endpoint"u8); + writer.WriteStringValue(Endpoint.AbsoluteUri); + writer.WritePropertyName("authentication"u8); + writer.WriteObjectValue(Authentication, options); + } + + OnYourDataEndpointVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataEndpointVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataEndpointVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataEndpointVectorizationSource DeserializeOnYourDataEndpointVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + Uri endpoint = default; + OnYourDataVectorSearchAuthenticationOptions authentication = default; + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("endpoint"u8)) + { + endpoint = new Uri(property.Value.GetString()); + continue; + } + if (property.NameEquals("authentication"u8)) + { + authentication = OnYourDataVectorSearchAuthenticationOptions.DeserializeOnYourDataVectorSearchAuthenticationOptions(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataEndpointVectorizationSource(type, serializedAdditionalRawData, endpoint, authentication); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataEndpointVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataEndpointVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataEndpointVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataEndpointVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataEndpointVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataEndpointVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.cs new file mode 100644 index 000000000000..5ab4f3198354 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataEndpointVectorizationSource.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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. + /// + public partial class OnYourDataEndpointVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// 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. + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + /// or is null. + public OnYourDataEndpointVectorizationSource(Uri endpoint, OnYourDataVectorSearchAuthenticationOptions authentication) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(authentication, nameof(authentication)); + + Type = OnYourDataVectorizationSourceType.Endpoint; + Endpoint = endpoint; + Authentication = authentication; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + /// 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. + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + internal OnYourDataEndpointVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData, Uri endpoint, OnYourDataVectorSearchAuthenticationOptions authentication) : base(type, serializedAdditionalRawData) + { + Endpoint = endpoint; + Authentication = authentication; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataEndpointVectorizationSource() + { + } + + /// 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. + public Uri Endpoint { get; } + /// + /// Specifies the authentication options to use when retrieving embeddings from the specified endpoint. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public OnYourDataVectorSearchAuthenticationOptions Authentication { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..16b93b7f4fba --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataIntegratedVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataIntegratedVectorizationSource)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + OnYourDataIntegratedVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataIntegratedVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataIntegratedVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataIntegratedVectorizationSource DeserializeOnYourDataIntegratedVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataIntegratedVectorizationSource(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataIntegratedVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataIntegratedVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataIntegratedVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataIntegratedVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataIntegratedVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataIntegratedVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.cs new file mode 100644 index 000000000000..89325cda307e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataIntegratedVectorizationSource.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Represents the integrated vectorizer defined within the search resource. + public partial class OnYourDataIntegratedVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + public OnYourDataIntegratedVectorizationSource() + { + Type = OnYourDataVectorizationSourceType.Integrated; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + internal OnYourDataIntegratedVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..92a1c24facd0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataKeyAndKeyIdAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + writer.WritePropertyName("key_id"u8); + writer.WriteStringValue(KeyId); + } + + OnYourDataKeyAndKeyIdAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataKeyAndKeyIdAuthenticationOptions DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + string keyId = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("key_id"u8)) + { + keyId = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataKeyAndKeyIdAuthenticationOptions(type, serializedAdditionalRawData, key, keyId); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataKeyAndKeyIdAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataKeyAndKeyIdAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataKeyAndKeyIdAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataKeyAndKeyIdAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.cs new file mode 100644 index 000000000000..469ac62213b4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataKeyAndKeyIdAuthenticationOptions.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an Elasticsearch key and key ID pair. + public partial class OnYourDataKeyAndKeyIdAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The key to use for authentication. + /// The key ID to use for authentication. + /// or is null. + public OnYourDataKeyAndKeyIdAuthenticationOptions(string key, string keyId) + { + Argument.AssertNotNull(key, nameof(key)); + Argument.AssertNotNull(keyId, nameof(keyId)); + + Type = OnYourDataAuthenticationType.KeyAndKeyId; + Key = key; + KeyId = keyId; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The key to use for authentication. + /// The key ID to use for authentication. + internal OnYourDataKeyAndKeyIdAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string key, string keyId) : base(type, serializedAdditionalRawData) + { + Key = key; + KeyId = keyId; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataKeyAndKeyIdAuthenticationOptions() + { + } + + /// The key to use for authentication. + public string Key { get; } + /// The key ID to use for authentication. + public string KeyId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..849178c965ee --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataModelIdVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataModelIdVectorizationSource)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("model_id"u8); + writer.WriteStringValue(ModelId); + } + + OnYourDataModelIdVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataModelIdVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataModelIdVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataModelIdVectorizationSource DeserializeOnYourDataModelIdVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string modelId = default; + OnYourDataVectorizationSourceType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("model_id"u8)) + { + modelId = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataModelIdVectorizationSource(type, serializedAdditionalRawData, modelId); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataModelIdVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataModelIdVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataModelIdVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataModelIdVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataModelIdVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataModelIdVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.cs new file mode 100644 index 000000000000..3db079445dbc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataModelIdVectorizationSource.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// 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®. + /// + public partial class OnYourDataModelIdVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + /// is null. + public OnYourDataModelIdVectorizationSource(string modelId) + { + Argument.AssertNotNull(modelId, nameof(modelId)); + + Type = OnYourDataVectorizationSourceType.ModelId; + ModelId = modelId; + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + internal OnYourDataModelIdVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData, string modelId) : base(type, serializedAdditionalRawData) + { + ModelId = modelId; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataModelIdVectorizationSource() + { + } + + /// The embedding model ID build inside the search service. Currently only supported by Elasticsearch®. + public string ModelId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..402eac36199c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataSystemAssignedManagedIdentityAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataSystemAssignedManagedIdentityAuthenticationOptions DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataSystemAssignedManagedIdentityAuthenticationOptions(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataSystemAssignedManagedIdentityAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataSystemAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataSystemAssignedManagedIdentityAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataSystemAssignedManagedIdentityAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.cs new file mode 100644 index 000000000000..734ef7b5d70c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataSystemAssignedManagedIdentityAuthenticationOptions.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a system-assigned managed identity. + public partial class OnYourDataSystemAssignedManagedIdentityAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + public OnYourDataSystemAssignedManagedIdentityAuthenticationOptions() + { + Type = OnYourDataAuthenticationType.SystemAssignedManagedIdentity; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + internal OnYourDataSystemAssignedManagedIdentityAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..10f1785dee97 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataUserAssignedManagedIdentityAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("managed_identity_resource_id"u8); + writer.WriteStringValue(ManagedIdentityResourceId); + } + + OnYourDataUserAssignedManagedIdentityAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataUserAssignedManagedIdentityAuthenticationOptions DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string managedIdentityResourceId = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("managed_identity_resource_id"u8)) + { + managedIdentityResourceId = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataUserAssignedManagedIdentityAuthenticationOptions(type, serializedAdditionalRawData, managedIdentityResourceId); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataUserAssignedManagedIdentityAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataUserAssignedManagedIdentityAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataUserAssignedManagedIdentityAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataUserAssignedManagedIdentityAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.cs new file mode 100644 index 000000000000..89ca44bf1441 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUserAssignedManagedIdentityAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a user-assigned managed identity. + public partial class OnYourDataUserAssignedManagedIdentityAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The resource ID of the user-assigned managed identity to use for authentication. + /// is null. + public OnYourDataUserAssignedManagedIdentityAuthenticationOptions(string managedIdentityResourceId) + { + Argument.AssertNotNull(managedIdentityResourceId, nameof(managedIdentityResourceId)); + + Type = OnYourDataAuthenticationType.UserAssignedManagedIdentity; + ManagedIdentityResourceId = managedIdentityResourceId; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The resource ID of the user-assigned managed identity to use for authentication. + internal OnYourDataUserAssignedManagedIdentityAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string managedIdentityResourceId) : base(type, serializedAdditionalRawData) + { + ManagedIdentityResourceId = managedIdentityResourceId; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataUserAssignedManagedIdentityAuthenticationOptions() + { + } + + /// The resource ID of the user-assigned managed identity to use for authentication. + public string ManagedIdentityResourceId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..e24640465b25 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataUsernameAndPasswordAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("username"u8); + writer.WriteStringValue(Username); + writer.WritePropertyName("password"u8); + writer.WriteStringValue(Password); + } + + OnYourDataUsernameAndPasswordAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataUsernameAndPasswordAuthenticationOptions DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string username = default; + string password = default; + OnYourDataAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("username"u8)) + { + username = property.Value.GetString(); + continue; + } + if (property.NameEquals("password"u8)) + { + password = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataUsernameAndPasswordAuthenticationOptions(type, serializedAdditionalRawData, username, password); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataUsernameAndPasswordAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataUsernameAndPasswordAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataUsernameAndPasswordAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataUsernameAndPasswordAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.cs new file mode 100644 index 000000000000..3b382f621f00 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataUsernameAndPasswordAuthenticationOptions.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using a username and password. + public partial class OnYourDataUsernameAndPasswordAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The username. + /// The password. + /// or is null. + public OnYourDataUsernameAndPasswordAuthenticationOptions(string username, string password) + { + Argument.AssertNotNull(username, nameof(username)); + Argument.AssertNotNull(password, nameof(password)); + + Type = OnYourDataAuthenticationType.UsernameAndPassword; + Username = username; + Password = password; + } + + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + /// The username. + /// The password. + internal OnYourDataUsernameAndPasswordAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData, string username, string password) : base(type, serializedAdditionalRawData) + { + Username = username; + Password = password; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataUsernameAndPasswordAuthenticationOptions() + { + } + + /// The username. + public string Username { get; } + /// The password. + public string Password { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..a5ac9f4ee41a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataVectorSearchAccessTokenAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("access_token"u8); + writer.WriteStringValue(AccessToken); + } + + OnYourDataVectorSearchAccessTokenAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataVectorSearchAccessTokenAuthenticationOptions DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string accessToken = default; + OnYourDataVectorSearchAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("access_token"u8)) + { + accessToken = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorSearchAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataVectorSearchAccessTokenAuthenticationOptions(type, serializedAdditionalRawData, accessToken); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorSearchAccessTokenAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAccessTokenAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataVectorSearchAccessTokenAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.cs new file mode 100644 index 000000000000..9a6cc8cd23c1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAccessTokenAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data vector search when using access token. + public partial class OnYourDataVectorSearchAccessTokenAuthenticationOptions : OnYourDataVectorSearchAuthenticationOptions + { + /// Initializes a new instance of . + /// The access token to use for authentication. + /// is null. + public OnYourDataVectorSearchAccessTokenAuthenticationOptions(string accessToken) + { + Argument.AssertNotNull(accessToken, nameof(accessToken)); + + Type = OnYourDataVectorSearchAuthenticationType.AccessToken; + AccessToken = accessToken; + } + + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + /// The access token to use for authentication. + internal OnYourDataVectorSearchAccessTokenAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData, string accessToken) : base(type, serializedAdditionalRawData) + { + AccessToken = accessToken; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataVectorSearchAccessTokenAuthenticationOptions() + { + } + + /// The access token to use for authentication. + public string AccessToken { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..3c9e8797c8e8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OnYourDataVectorSearchApiKeyAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("key"u8); + writer.WriteStringValue(Key); + } + + OnYourDataVectorSearchApiKeyAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataVectorSearchApiKeyAuthenticationOptions DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string key = default; + OnYourDataVectorSearchAuthenticationType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("key"u8)) + { + key = property.Value.GetString(); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorSearchAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OnYourDataVectorSearchApiKeyAuthenticationOptions(type, serializedAdditionalRawData, key); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorSearchApiKeyAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchApiKeyAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new OnYourDataVectorSearchApiKeyAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.cs new file mode 100644 index 000000000000..6cb88743fc8a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchApiKeyAuthenticationOptions.cs @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The authentication options for Azure OpenAI On Your Data when using an API key. + public partial class OnYourDataVectorSearchApiKeyAuthenticationOptions : OnYourDataVectorSearchAuthenticationOptions + { + /// Initializes a new instance of . + /// The API key to use for authentication. + /// is null. + public OnYourDataVectorSearchApiKeyAuthenticationOptions(string key) + { + Argument.AssertNotNull(key, nameof(key)); + + Type = OnYourDataVectorSearchAuthenticationType.ApiKey; + Key = key; + } + + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + /// The API key to use for authentication. + internal OnYourDataVectorSearchApiKeyAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData, string key) : base(type, serializedAdditionalRawData) + { + Key = key; + } + + /// Initializes a new instance of for deserialization. + internal OnYourDataVectorSearchApiKeyAuthenticationOptions() + { + } + + /// The API key to use for authentication. + public string Key { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..3446ef5b1442 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownOnYourDataVectorSearchAuthenticationOptions))] + public partial class OnYourDataVectorSearchAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OnYourDataVectorSearchAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + + internal static OnYourDataVectorSearchAuthenticationOptions DeserializeOnYourDataVectorSearchAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "access_token": return OnYourDataVectorSearchAccessTokenAuthenticationOptions.DeserializeOnYourDataVectorSearchAccessTokenAuthenticationOptions(element, options); + case "api_key": return OnYourDataVectorSearchApiKeyAuthenticationOptions.DeserializeOnYourDataVectorSearchApiKeyAuthenticationOptions(element, options); + } + } + return UnknownOnYourDataVectorSearchAuthenticationOptions.DeserializeUnknownOnYourDataVectorSearchAuthenticationOptions(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorSearchAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OnYourDataVectorSearchAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.cs new file mode 100644 index 000000000000..077fa22c2793 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationOptions.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// The authentication options for Azure OpenAI On Your Data vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include and . + /// + public abstract partial class OnYourDataVectorSearchAuthenticationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected OnYourDataVectorSearchAuthenticationOptions() + { + } + + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + internal OnYourDataVectorSearchAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The type of authentication to use. + internal OnYourDataVectorSearchAuthenticationType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationType.cs new file mode 100644 index 000000000000..5b91b4f56ba1 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorSearchAuthenticationType.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The authentication types supported with Azure OpenAI On Your Data vector search. + internal readonly partial struct OnYourDataVectorSearchAuthenticationType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataVectorSearchAuthenticationType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ApiKeyValue = "api_key"; + private const string AccessTokenValue = "access_token"; + + /// Authentication via API key. + public static OnYourDataVectorSearchAuthenticationType ApiKey { get; } = new OnYourDataVectorSearchAuthenticationType(ApiKeyValue); + /// Authentication via access token. + public static OnYourDataVectorSearchAuthenticationType AccessToken { get; } = new OnYourDataVectorSearchAuthenticationType(AccessTokenValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataVectorSearchAuthenticationType left, OnYourDataVectorSearchAuthenticationType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataVectorSearchAuthenticationType left, OnYourDataVectorSearchAuthenticationType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataVectorSearchAuthenticationType(string value) => new OnYourDataVectorSearchAuthenticationType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataVectorSearchAuthenticationType other && Equals(other); + /// + public bool Equals(OnYourDataVectorSearchAuthenticationType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..bb77406a05fa --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.Serialization.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + [PersistableModelProxy(typeof(UnknownOnYourDataVectorizationSource))] + public partial class OnYourDataVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OnYourDataVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + + internal static OnYourDataVectorizationSource DeserializeOnYourDataVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + if (element.TryGetProperty("type", out JsonElement discriminator)) + { + switch (discriminator.GetString()) + { + case "deployment_name": return OnYourDataDeploymentNameVectorizationSource.DeserializeOnYourDataDeploymentNameVectorizationSource(element, options); + case "endpoint": return OnYourDataEndpointVectorizationSource.DeserializeOnYourDataEndpointVectorizationSource(element, options); + case "integrated": return OnYourDataIntegratedVectorizationSource.DeserializeOnYourDataIntegratedVectorizationSource(element, options); + case "model_id": return OnYourDataModelIdVectorizationSource.DeserializeOnYourDataModelIdVectorizationSource(element, options); + } + } + return UnknownOnYourDataVectorizationSource.DeserializeUnknownOnYourDataVectorizationSource(element, options); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OnYourDataVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.cs new file mode 100644 index 000000000000..c675da983dd8 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSource.cs @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// An abstract representation of a vectorization source for Azure OpenAI On Your Data with vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public abstract partial class OnYourDataVectorizationSource + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private protected IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + protected OnYourDataVectorizationSource() + { + } + + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + internal OnYourDataVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData) + { + Type = type; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The type of vectorization source to use. + internal OnYourDataVectorizationSourceType Type { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSourceType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSourceType.cs new file mode 100644 index 000000000000..1f951716f33e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OnYourDataVectorizationSourceType.cs @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// + /// Represents the available sources Azure OpenAI On Your Data can use to configure vectorization of data for use with + /// vector search. + /// + internal readonly partial struct OnYourDataVectorizationSourceType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OnYourDataVectorizationSourceType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string EndpointValue = "endpoint"; + private const string DeploymentNameValue = "deployment_name"; + private const string ModelIdValue = "model_id"; + private const string IntegratedValue = "integrated"; + + /// Represents vectorization performed by public service calls to an Azure OpenAI embedding model. + public static OnYourDataVectorizationSourceType Endpoint { get; } = new OnYourDataVectorizationSourceType(EndpointValue); + /// + /// Represents an Ada model deployment name to use. This model deployment must be in the same Azure OpenAI resource, but + /// On Your Data will use this model deployment via an internal call rather than a public one, which enables vector + /// search even in private networks. + /// + public static OnYourDataVectorizationSourceType DeploymentName { get; } = new OnYourDataVectorizationSourceType(DeploymentNameValue); + /// + /// Represents a specific embedding model ID as defined in the search service. + /// Currently only supported by Elasticsearch®. + /// + public static OnYourDataVectorizationSourceType ModelId { get; } = new OnYourDataVectorizationSourceType(ModelIdValue); + /// Represents the integrated vectorizer defined within the search resource. + public static OnYourDataVectorizationSourceType Integrated { get; } = new OnYourDataVectorizationSourceType(IntegratedValue); + /// Determines if two values are the same. + public static bool operator ==(OnYourDataVectorizationSourceType left, OnYourDataVectorizationSourceType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OnYourDataVectorizationSourceType left, OnYourDataVectorizationSourceType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OnYourDataVectorizationSourceType(string value) => new OnYourDataVectorizationSourceType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OnYourDataVectorizationSourceType other && Equals(other); + /// + public bool Equals(OnYourDataVectorizationSourceType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClient.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClient.cs new file mode 100644 index 000000000000..fb3171366f86 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClient.cs @@ -0,0 +1,2859 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.AI.OpenAI +{ + // Data plane generated client. + /// The OpenAI service client. + public partial class OpenAIClient + { + private const string AuthorizationHeader = "api-key"; + private readonly AzureKeyCredential _keyCredential; + private static readonly string[] AuthorizationScopes = new string[] { "https://cognitiveservices.azure.com/.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of OpenAIClient for mocking. + protected OpenAIClient() + { + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// or is null. + public OpenAIClient(Uri endpoint, AzureKeyCredential credential) : this(endpoint, credential, new OpenAIClientOptions()) + { + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// or is null. + public OpenAIClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new OpenAIClientOptions()) + { + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public OpenAIClient(Uri endpoint, AzureKeyCredential credential, OpenAIClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new OpenAIClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _keyCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new AzureKeyCredentialPolicy(_keyCredential, AuthorizationHeader) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// Initializes a new instance of OpenAIClient. + /// + /// Supported Cognitive Services endpoints (protocol and hostname, for example: + /// https://westus.api.cognitive.microsoft.com). + /// + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public OpenAIClient(Uri endpoint, TokenCredential credential, OpenAIClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new OpenAIClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + _apiVersion = options.Version; + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranscriptionAsPlainTextAsync(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranscriptionAsPlainTextAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(response.Content.ToString(), response); + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranscriptionAsPlainText(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranscriptionAsPlainText(deploymentId, content, content.ContentType, context); + return Response.FromValue(response.Content.ToString(), response); + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranscriptionAsPlainTextAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsPlainTextRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranscriptionAsPlainText(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsPlainTextRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranscriptionAsResponseObjectAsync(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranscriptionAsResponseObjectAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(AudioTranscription.FromResponse(response), response); + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio transcription request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranscriptionAsResponseObject(string deploymentId, AudioTranscriptionOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranscriptionAsResponseObject(deploymentId, content, content.ContentType, context); + return Response.FromValue(AudioTranscription.FromResponse(response), response); + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranscriptionAsResponseObjectAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsResponseObjectRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranscriptionAsResponseObject(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranscriptionAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranscriptionAsResponseObjectRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranslationAsPlainTextAsync(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranslationAsPlainTextAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(response.Content.ToString(), response); + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranslationAsPlainText(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranslationAsPlainText(deploymentId, content, content.ContentType, context); + return Response.FromValue(response.Content.ToString(), response); + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranslationAsPlainTextAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsPlainTextRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranslationAsPlainText(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsPlainText"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsPlainTextRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetAudioTranslationAsResponseObjectAsync(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetAudioTranslationAsResponseObjectAsync(deploymentId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(AudioTranslation.FromResponse(response), response); + } + + /// Gets English language transcribed text and associated metadata from provided spoken audio data. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The configuration information for an audio translation request. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetAudioTranslationAsResponseObject(string deploymentId, AudioTranslationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using MultipartFormDataRequestContent content = body.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetAudioTranslationAsResponseObject(deploymentId, content, content.ContentType, context); + return Response.FromValue(AudioTranslation.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetAudioTranslationAsResponseObjectAsync(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsResponseObjectRequest(deploymentId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets English language transcribed text and associated metadata from provided spoken audio data. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The content type for the operation. Always multipart/form-data for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetAudioTranslationAsResponseObject(string deploymentId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetAudioTranslationAsResponseObject"); + scope.Start(); + try + { + using HttpMessage message = CreateGetAudioTranslationAsResponseObjectRequest(deploymentId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetCompletionsAsync(string deploymentId, CompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetCompletionsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(Completions.FromResponse(response), response); + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetCompletions(string deploymentId, CompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetCompletions(deploymentId, content, context); + return Response.FromValue(Completions.FromResponse(response), response); + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetCompletionsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetCompletionsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetCompletions(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetCompletionsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for a chat completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetChatCompletionsAsync(string deploymentId, ChatCompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetChatCompletionsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(ChatCompletions.FromResponse(response), response); + } + + /// + /// 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. + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// The configuration information for a chat completions request. + /// Completions support a wide variety of tasks and generate text that continues from or "completes" + /// provided prompt data. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetChatCompletions(string deploymentId, ChatCompletionsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetChatCompletions(deploymentId, content, context); + return Response.FromValue(ChatCompletions.FromResponse(response), response); + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetChatCompletionsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetChatCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetChatCompletionsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] 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. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetChatCompletions(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetChatCompletions"); + scope.Start(); + try + { + using HttpMessage message = CreateGetChatCompletionsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Creates an image given a prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// Represents the request data used to generate images. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetImageGenerationsAsync(string deploymentId, ImageGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetImageGenerationsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(ImageGenerations.FromResponse(response), response); + } + + /// Creates an image given a prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// Represents the request data used to generate images. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetImageGenerations(string deploymentId, ImageGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetImageGenerations(deploymentId, content, context); + return Response.FromValue(ImageGenerations.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates an image given a prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetImageGenerationsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetImageGenerations"); + scope.Start(); + try + { + using HttpMessage message = CreateGetImageGenerationsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates an image given a prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetImageGenerations(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetImageGenerations"); + scope.Start(); + try + { + using HttpMessage message = CreateGetImageGenerationsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Generates text-to-speech audio from the input text. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// A representation of the request options that control the behavior of a text-to-speech operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GenerateSpeechFromTextAsync(string deploymentId, SpeechGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GenerateSpeechFromTextAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(response.Content, response); + } + + /// Generates text-to-speech audio from the input text. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// A representation of the request options that control the behavior of a text-to-speech operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GenerateSpeechFromText(string deploymentId, SpeechGenerationOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GenerateSpeechFromText(deploymentId, content, context); + return Response.FromValue(response.Content, response); + } + + /// + /// [Protocol Method] Generates text-to-speech audio from the input text. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GenerateSpeechFromTextAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GenerateSpeechFromText"); + scope.Start(); + try + { + using HttpMessage message = CreateGenerateSpeechFromTextRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Generates text-to-speech audio from the input text. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GenerateSpeechFromText(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GenerateSpeechFromText"); + scope.Start(); + try + { + using HttpMessage message = CreateGenerateSpeechFromTextRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Return the embeddings for a given prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetEmbeddingsAsync(string deploymentId, EmbeddingsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetEmbeddingsAsync(deploymentId, content, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Embeddings.FromResponse(response), response); + } + + /// Return the embeddings for a given prompt. + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// + /// 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. + /// + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetEmbeddings(string deploymentId, EmbeddingsOptions body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetEmbeddings(deploymentId, content, context); + return Response.FromValue(OpenAI.Embeddings.FromResponse(response), response); + } + + /// + /// [Protocol Method] Return the embeddings for a given prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetEmbeddingsAsync(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetEmbeddings"); + scope.Start(); + try + { + using HttpMessage message = CreateGetEmbeddingsRequest(deploymentId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Return the embeddings for a given prompt. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Specifies either the model deployment name (when using Azure OpenAI) or model name (when using non-Azure OpenAI) to use for this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetEmbeddings(string deploymentId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(deploymentId, nameof(deploymentId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetEmbeddings"); + scope.Start(); + try + { + using HttpMessage message = CreateGetEmbeddingsRequest(deploymentId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + public virtual async Task> GetFilesAsync(FilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetFilesAsync(purpose?.ToString(), context).ConfigureAwait(false); + return Response.FromValue(FileListResponse.FromResponse(response), response); + } + + /// Gets a list of previously uploaded files. + /// A value that, when provided, limits list results to files matching the corresponding purpose. + /// The cancellation token to use. + public virtual Response GetFiles(FilePurpose? purpose = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetFiles(purpose?.ToString(), context); + return Response.FromValue(FileListResponse.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetFilesAsync(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFilesRequest(purpose, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of previously uploaded files. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// A value that, when provided, limits list results to files matching the corresponding purpose. Allowed values: "fine-tune" | "fine-tune-results" | "assistants" | "assistants_output" | "batch" | "batch_output" | "vision". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetFiles(string purpose, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFiles"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFilesRequest(purpose, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Uploads a file for use by other operations. + /// The file and its purpose to upload. + /// The cancellation token to use. + /// is null. + public virtual async Task> UploadFileAsync(UploadFileRequest file, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(file, nameof(file)); + + using MultipartFormDataRequestContent content = file.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await UploadFileAsync(content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// Uploads a file for use by other operations. + /// The file and its purpose to upload. + /// The cancellation token to use. + /// is null. + public virtual Response UploadFile(UploadFileRequest file, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(file, nameof(file)); + + using MultipartFormDataRequestContent content = file.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = UploadFile(content, content.ContentType, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task UploadFileAsync(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Uploads a file for use by other operations. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The 'content-type' header value, always 'multipart/format-data' for this operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response UploadFile(RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.UploadFile"); + scope.Start(); + try + { + using HttpMessage message = CreateUploadFileRequest(content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Delete a previously uploaded file. + /// The ID of the file to delete. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> DeleteFileAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await DeleteFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(FileDeletionStatus.FromResponse(response), response); + } + + /// Delete a previously uploaded file. + /// The ID of the file to delete. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response DeleteFile(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = DeleteFile(fileId, context); + return Response.FromValue(FileDeletionStatus.FromResponse(response), response); + } + + /// + /// [Protocol Method] Delete a previously uploaded file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task DeleteFileAsync(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.DeleteFile"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteFileRequest(fileId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Delete a previously uploaded file. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to delete. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response DeleteFile(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.DeleteFile"); + scope.Start(); + try + { + using HttpMessage message = CreateDeleteFileRequest(fileId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetFileAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFile(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetFile(fileId, context); + return Response.FromValue(OpenAIFile.FromResponse(response), response); + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetFileAsync(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFile"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileRequest(fileId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetFile(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFile"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileRequest(fileId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetFileContentAsync(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetFileContentAsync(fileId, context).ConfigureAwait(false); + return Response.FromValue(response.Content, response); + } + + /// Returns information about a specific file. Does not retrieve file content. + /// The ID of the file to retrieve. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetFileContent(string fileId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetFileContent(fileId, context); + return Response.FromValue(response.Content, response); + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetFileContentAsync(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFileContent"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileContentRequest(fileId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Returns information about a specific file. Does not retrieve file content. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the file to retrieve. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetFileContent(string fileId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(fileId, nameof(fileId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetFileContent"); + scope.Start(); + try + { + using HttpMessage message = CreateGetFileContentRequest(fileId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets a list of all batches owned by the Azure OpenAI resource. + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The cancellation token to use. + public virtual async Task> GetBatchesAsync(string after = null, int? limit = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetBatchesAsync(after, limit, context).ConfigureAwait(false); + return Response.FromValue(OpenAIPageableListOfBatch.FromResponse(response), response); + } + + /// Gets a list of all batches owned by the Azure OpenAI resource. + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The cancellation token to use. + public virtual Response GetBatches(string after = null, int? limit = null, CancellationToken cancellationToken = default) + { + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetBatches(after, limit, context); + return Response.FromValue(OpenAIPageableListOfBatch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets a list of all batches owned by the Azure OpenAI resource. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetBatchesAsync(string after, int? limit, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatches"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchesRequest(after, limit, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets a list of all batches owned by the Azure OpenAI resource. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Identifier for the last event from the previous pagination request. + /// Number of batches to retrieve. Defaults to 20. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetBatches(string after, int? limit, RequestContext context) + { + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatches"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchesRequest(after, limit, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// The specification of the batch to create and execute. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateBatchAsync(BatchCreateRequest createBatchRequest, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(createBatchRequest, nameof(createBatchRequest)); + + using RequestContent content = createBatchRequest.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateBatchAsync(content, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// The specification of the batch to create and execute. + /// The cancellation token to use. + /// is null. + public virtual Response CreateBatch(BatchCreateRequest createBatchRequest, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(createBatchRequest, nameof(createBatchRequest)); + + using RequestContent content = createBatchRequest.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateBatch(content, context); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CreateBatchAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateBatchRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates and executes a batch from an uploaded file of requests. + /// Response includes details of the enqueued job including job status. + /// The ID of the result file is added to the response once complete. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CreateBatch(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateBatchRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> GetBatchAsync(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await GetBatchAsync(batchId, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response GetBatch(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = GetBatch(batchId, context); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task GetBatchAsync(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchRequest(batchId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response GetBatch(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.GetBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateGetBatchRequest(batchId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CancelBatchAsync(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CancelBatchAsync(batchId, context).ConfigureAwait(false); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// Gets details for a single batch specified by the given batchID. + /// The identifier of the batch. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CancelBatch(string batchId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CancelBatch(batchId, context); + return Response.FromValue(OpenAI.Batch.FromResponse(response), response); + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CancelBatchAsync(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelBatchRequest(batchId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Gets details for a single batch specified by the given batchID. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The identifier of the batch. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CancelBatch(string batchId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(batchId, nameof(batchId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelBatch"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelBatchRequest(batchId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// The request body for the operation options. + /// The cancellation token to use. + /// is null. + public virtual async Task> CreateUploadAsync(CreateUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CreateUploadAsync(content, context).ConfigureAwait(false); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// The request body for the operation options. + /// The cancellation token to use. + /// is null. + public virtual Response CreateUpload(CreateUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CreateUpload(content, context); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// [Protocol Method] Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CreateUploadAsync(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateUploadRequest(content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it. + /// + /// Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. + /// + /// For certain purposes, the correct mime_type must be specified. Please refer to documentation for the supported MIME types for your use case. + /// + /// For guidance on the proper filename extensions for each purpose, please follow the documentation on creating a File. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CreateUpload(RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CreateUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCreateUploadRequest(content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// The ID of the upload associated with this operation. + /// The request body data payload for the operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> AddUploadPartAsync(string uploadId, AddUploadPartRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using MultipartFormDataRequestContent content = requestBody.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await AddUploadPartAsync(uploadId, content, content.ContentType, context).ConfigureAwait(false); + return Response.FromValue(UploadPart.FromResponse(response), response); + } + + /// + /// Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// The ID of the upload associated with this operation. + /// The request body data payload for the operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response AddUploadPart(string uploadId, AddUploadPartRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using MultipartFormDataRequestContent content = requestBody.ToMultipartRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = AddUploadPart(uploadId, content, content.ContentType, context); + return Response.FromValue(UploadPart.FromResponse(response), response); + } + + /// + /// [Protocol Method] Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The multipart/form-data content-type header for the operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task AddUploadPartAsync(string uploadId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.AddUploadPart"); + scope.Start(); + try + { + using HttpMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Adds a Part to an Upload object. A Part represents a chunk of bytes from the file you are trying to upload. + /// + /// Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + /// + /// It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you complete the Upload. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The multipart/form-data content-type header for the operation. Allowed values: "multipart/form-data". + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response AddUploadPart(string uploadId, RequestContent content, string contentType, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.AddUploadPart"); + scope.Start(); + try + { + using HttpMessage message = CreateAddUploadPartRequest(uploadId, content, contentType, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// The ID of the upload associated with this operation. + /// The request body for the completion operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CompleteUploadAsync(string uploadId, CompleteUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CompleteUploadAsync(uploadId, content, context).ConfigureAwait(false); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// The ID of the upload associated with this operation. + /// The request body for the completion operation. + /// The cancellation token to use. + /// or is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CompleteUpload(string uploadId, CompleteUploadRequest requestBody, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(requestBody, nameof(requestBody)); + + using RequestContent content = requestBody.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CompleteUpload(uploadId, content, context); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// [Protocol Method] Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CompleteUploadAsync(string uploadId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CompleteUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCompleteUploadRequest(uploadId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Completes the Upload. + /// + /// Within the returned Upload object, there is a nested File object that is ready to use in the rest of the platform. + /// + /// You can specify the order of the Parts by passing in an ordered list of the Part IDs. + /// + /// The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CompleteUpload(string uploadId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CompleteUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCompleteUploadRequest(uploadId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// The ID of the upload associated with this operation. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual async Task> CancelUploadAsync(string uploadId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await CancelUploadAsync(uploadId, context).ConfigureAwait(false); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// The ID of the upload associated with this operation. + /// The cancellation token to use. + /// is null. + /// is an empty string, and was expected to be non-empty. + public virtual Response CancelUpload(string uploadId, CancellationToken cancellationToken = default) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + RequestContext context = FromCancellationToken(cancellationToken); + Response response = CancelUpload(uploadId, context); + return Response.FromValue(Upload.FromResponse(response), response); + } + + /// + /// [Protocol Method] Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual async Task CancelUploadAsync(string uploadId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelUploadRequest(uploadId, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Cancels the Upload. No Parts may be added after an Upload is cancelled. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// The ID of the upload associated with this operation. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// is null. + /// is an empty string, and was expected to be non-empty. + /// Service returned a non-success status code. + /// The response returned from the service. + internal virtual Response CancelUpload(string uploadId, RequestContext context) + { + Argument.AssertNotNullOrEmpty(uploadId, nameof(uploadId)); + + using var scope = ClientDiagnostics.CreateScope("OpenAIClient.CancelUpload"); + scope.Start(); + try + { + using HttpMessage message = CreateCancelUploadRequest(uploadId, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateGetAudioTranscriptionAsPlainTextRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/transcriptions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "text/plain"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetAudioTranscriptionAsResponseObjectRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/transcriptions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetAudioTranslationAsPlainTextRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/translations", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "text/plain"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetAudioTranslationAsResponseObjectRequest(string deploymentId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/translations", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetCompletionsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/completions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetChatCompletionsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/chat/completions", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetImageGenerationsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/images/generations", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGenerateSpeechFromTextRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/audio/speech", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/octet-stream"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetEmbeddingsRequest(string deploymentId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/deployments/", false); + uri.AppendPath(deploymentId, true); + uri.AppendPath("/embeddings", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetFilesRequest(string purpose, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files", false); + if (purpose != null) + { + uri.AppendQuery("purpose", purpose, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateUploadFileRequest(RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateDeleteFileRequest(string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Delete; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetFileRequest(string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateGetFileContentRequest(string fileId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/files/", false); + uri.AppendPath(fileId, true); + uri.AppendPath("/content", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/octet-stream"); + return message; + } + + internal HttpMessage CreateGetBatchesRequest(string after, int? limit, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches", false); + if (after != null) + { + uri.AppendQuery("after", after, true); + } + if (limit != null) + { + uri.AppendQuery("limit", limit.Value, true); + } + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateBatchRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier201); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateGetBatchRequest(string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Get; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches/", false); + uri.AppendPath(batchId, true); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCancelBatchRequest(string batchId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/batches/", false); + uri.AppendPath(batchId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + internal HttpMessage CreateCreateUploadRequest(RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateAddUploadPartRequest(string uploadId, RequestContent content, string contentType, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/parts", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", contentType); + request.Content = content; + return message; + } + + internal HttpMessage CreateCompleteUploadRequest(string uploadId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/complete", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateCancelUploadRequest(string uploadId, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendRaw("/openai", false); + uri.AppendPath("/uploads/", false); + uri.AppendPath(uploadId, true); + uri.AppendPath("/cancel", false); + request.Uri = uri; + request.Headers.Add("Accept", "application/json"); + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + private static ResponseClassifier _responseClassifier201; + private static ResponseClassifier ResponseClassifier201 => _responseClassifier201 ??= new StatusCodeClassifier(stackalloc ushort[] { 201 }); + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClientOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClientOptions.cs new file mode 100644 index 000000000000..4b9e8a6b37a5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIClientOptions.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + /// Client options for OpenAIClient. + public partial class OpenAIClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2025_01_01_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2022-12-01". + V2022_12_01 = 1, + /// Service version "2023-05-15". + V2023_05_15 = 2, + /// Service version "2023-06-01-preview". + V2023_06_01_Preview = 3, + /// Service version "2023-07-01-preview". + V2023_07_01_Preview = 4, + /// Service version "2024-02-01". + V2024_02_01 = 5, + /// Service version "2024-02-15-preview". + V2024_02_15_Preview = 6, + /// Service version "2024-03-01-preview". + V2024_03_01_Preview = 7, + /// Service version "2024-04-01-preview". + V2024_04_01_Preview = 8, + /// Service version "2024-05-01-preview". + V2024_05_01_Preview = 9, + /// Service version "2024-06-01". + V2024_06_01 = 10, + /// Service version "2024-07-01-preview". + V2024_07_01_Preview = 11, + /// Service version "2024-08-01-preview". + V2024_08_01_Preview = 12, + /// Service version "2024-09-01-preview". + V2024_09_01_Preview = 13, + /// Service version "2024-10-01-preview". + V2024_10_01_Preview = 14, + /// Service version "2025-01-01-preview". + V2025_01_01_Preview = 15, + } + + internal string Version { get; } + + /// Initializes new instance of OpenAIClientOptions. + public OpenAIClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2022_12_01 => "2022-12-01", + ServiceVersion.V2023_05_15 => "2023-05-15", + ServiceVersion.V2023_06_01_Preview => "2023-06-01-preview", + ServiceVersion.V2023_07_01_Preview => "2023-07-01-preview", + ServiceVersion.V2024_02_01 => "2024-02-01", + ServiceVersion.V2024_02_15_Preview => "2024-02-15-preview", + ServiceVersion.V2024_03_01_Preview => "2024-03-01-preview", + ServiceVersion.V2024_04_01_Preview => "2024-04-01-preview", + ServiceVersion.V2024_05_01_Preview => "2024-05-01-preview", + ServiceVersion.V2024_06_01 => "2024-06-01", + ServiceVersion.V2024_07_01_Preview => "2024-07-01-preview", + ServiceVersion.V2024_08_01_Preview => "2024-08-01-preview", + ServiceVersion.V2024_09_01_Preview => "2024-09-01-preview", + ServiceVersion.V2024_10_01_Preview => "2024-10-01-preview", + ServiceVersion.V2025_01_01_Preview => "2025-01-01-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.Serialization.cs new file mode 100644 index 000000000000..bcdbb39ac35e --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.Serialization.cs @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OpenAIFile : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAIFile)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + if (Optional.IsDefined(Status)) + { + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.Value.ToString()); + } + if (Optional.IsDefined(StatusDetails)) + { + writer.WritePropertyName("status_details"u8); + writer.WriteStringValue(StatusDetails); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OpenAIFile IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAIFile)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOpenAIFile(document.RootElement, options); + } + + internal static OpenAIFile DeserializeOpenAIFile(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OpenAIFileObject @object = default; + string id = default; + int bytes = default; + string filename = default; + DateTimeOffset createdAt = default; + FilePurpose purpose = default; + FileState? status = default; + string statusDetails = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new OpenAIFileObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new FilePurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("status"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + status = new FileState(property.Value.GetString()); + continue; + } + if (property.NameEquals("status_details"u8)) + { + statusDetails = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAIFile( + @object, + id, + bytes, + filename, + createdAt, + purpose, + status, + statusDetails, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OpenAIFile)} does not support writing '{options.Format}' format."); + } + } + + OpenAIFile IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOpenAIFile(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAIFile)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAIFile FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOpenAIFile(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.cs similarity index 51% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.cs index 119a216efc63..a9eddeb3b1c6 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/AssistantFile.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFile.cs @@ -8,10 +8,10 @@ using System; using System.Collections.Generic; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - /// Information about a file attached to an assistant, as used by tools that can read files. - public partial class AssistantFile + /// Represents an assistant that can call the model and use tools. + public partial class OpenAIFile { /// /// Keeps track of any properties unknown to the library. @@ -45,47 +45,69 @@ public partial class AssistantFile /// private IDictionary _serializedAdditionalRawData; - /// Initializes a new instance of . + /// Initializes a new instance of . /// The identifier, which can be referenced in API endpoints. + /// The size of the file, in bytes. + /// The name of the file. /// The Unix timestamp, in seconds, representing when this object was created. - /// The assistant ID that the file is attached to. - /// or is null. - internal AssistantFile(string id, DateTimeOffset createdAt, string assistantId) + /// The intended purpose of a file. + /// or is null. + internal OpenAIFile(string id, int bytes, string filename, DateTimeOffset createdAt, FilePurpose purpose) { Argument.AssertNotNull(id, nameof(id)); - Argument.AssertNotNull(assistantId, nameof(assistantId)); + Argument.AssertNotNull(filename, nameof(filename)); Id = id; + Bytes = bytes; + Filename = filename; CreatedAt = createdAt; - AssistantId = assistantId; + Purpose = purpose; } - /// Initializes a new instance of . + /// Initializes a new instance of . + /// The object type, which is always 'file'. /// The identifier, which can be referenced in API endpoints. - /// The object type, which is always 'assistant.file'. + /// The size of the file, in bytes. + /// The name of the file. /// The Unix timestamp, in seconds, representing when this object was created. - /// The assistant ID that the file is attached to. + /// The intended purpose of a file. + /// The state of the file. This field is available in Azure OpenAI only. + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. /// Keeps track of any properties unknown to the library. - internal AssistantFile(string id, string @object, DateTimeOffset createdAt, string assistantId, IDictionary serializedAdditionalRawData) + internal OpenAIFile(OpenAIFileObject @object, string id, int bytes, string filename, DateTimeOffset createdAt, FilePurpose purpose, FileState? status, string statusDetails, IDictionary serializedAdditionalRawData) { - Id = id; Object = @object; + Id = id; + Bytes = bytes; + Filename = filename; CreatedAt = createdAt; - AssistantId = assistantId; + Purpose = purpose; + Status = status; + StatusDetails = statusDetails; _serializedAdditionalRawData = serializedAdditionalRawData; } - /// Initializes a new instance of for deserialization. - internal AssistantFile() + /// Initializes a new instance of for deserialization. + internal OpenAIFile() { } + /// The object type, which is always 'file'. + public OpenAIFileObject Object { get; } = OpenAIFileObject.File; + /// The identifier, which can be referenced in API endpoints. public string Id { get; } - + /// The size of the file, in bytes. + public int Bytes { get; } + /// The name of the file. + public string Filename { get; } /// The Unix timestamp, in seconds, representing when this object was created. public DateTimeOffset CreatedAt { get; } - /// The assistant ID that the file is attached to. - public string AssistantId { get; } + /// The intended purpose of a file. + public FilePurpose Purpose { get; } + /// The state of the file. This field is available in Azure OpenAI only. + public FileState? Status { get; } + /// The error message with details in case processing of this file failed. This field is available in Azure OpenAI only. + public string StatusDetails { get; } } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFileObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFileObject.cs new file mode 100644 index 000000000000..8268140265ee --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIFileObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The OpenAIFile_object. + public readonly partial struct OpenAIFileObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OpenAIFileObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string FileValue = "file"; + + /// file. + public static OpenAIFileObject File { get; } = new OpenAIFileObject(FileValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIFileObject left, OpenAIFileObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIFileObject left, OpenAIFileObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIFileObject(string value) => new OpenAIFileObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OpenAIFileObject other && Equals(other); + /// + public bool Equals(OpenAIFileObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.Serialization.cs new file mode 100644 index 000000000000..68feaa9f5c9c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.Serialization.cs @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class OpenAIPageableListOfBatch : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAIPageableListOfBatch)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsCollectionDefined(Data)) + { + writer.WritePropertyName("data"u8); + writer.WriteStartArray(); + foreach (var item in Data) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(FirstId)) + { + writer.WritePropertyName("first_id"u8); + writer.WriteStringValue(FirstId); + } + if (Optional.IsDefined(LastId)) + { + writer.WritePropertyName("last_id"u8); + writer.WriteStringValue(LastId); + } + if (Optional.IsDefined(HasMore)) + { + writer.WritePropertyName("has_more"u8); + writer.WriteBooleanValue(HasMore.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + OpenAIPageableListOfBatch IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OpenAIPageableListOfBatch)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOpenAIPageableListOfBatch(document.RootElement, options); + } + + internal static OpenAIPageableListOfBatch DeserializeOpenAIPageableListOfBatch(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OpenAIPageableListOfBatchObject @object = default; + IReadOnlyList data = default; + string firstId = default; + string lastId = default; + bool? hasMore = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("object"u8)) + { + @object = new OpenAIPageableListOfBatchObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("data"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(OpenAI.Batch.DeserializeBatch(item, options)); + } + data = array; + continue; + } + if (property.NameEquals("first_id"u8)) + { + firstId = property.Value.GetString(); + continue; + } + if (property.NameEquals("last_id"u8)) + { + lastId = property.Value.GetString(); + continue; + } + if (property.NameEquals("has_more"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + hasMore = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new OpenAIPageableListOfBatch( + @object, + data ?? new ChangeTrackingList(), + firstId, + lastId, + hasMore, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OpenAIPageableListOfBatch)} does not support writing '{options.Format}' format."); + } + } + + OpenAIPageableListOfBatch IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOpenAIPageableListOfBatch(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OpenAIPageableListOfBatch)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static OpenAIPageableListOfBatch FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOpenAIPageableListOfBatch(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.cs new file mode 100644 index 000000000000..16be6cb0109c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatch.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The response data for a requested list of items. + public partial class OpenAIPageableListOfBatch + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal OpenAIPageableListOfBatch() + { + Data = new ChangeTrackingList(); + } + + /// Initializes a new instance of . + /// The object type, which is always list. + /// The requested list of items. + /// The first ID represented in this list. + /// The last ID represented in this list. + /// A value indicating whether there are additional values available not captured in this list. + /// Keeps track of any properties unknown to the library. + internal OpenAIPageableListOfBatch(OpenAIPageableListOfBatchObject @object, IReadOnlyList data, string firstId, string lastId, bool? hasMore, IDictionary serializedAdditionalRawData) + { + Object = @object; + Data = data; + FirstId = firstId; + LastId = lastId; + HasMore = hasMore; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// The object type, which is always list. + public OpenAIPageableListOfBatchObject Object { get; } = OpenAIPageableListOfBatchObject.List; + + /// The requested list of items. + public IReadOnlyList Data { get; } + /// The first ID represented in this list. + public string FirstId { get; } + /// The last ID represented in this list. + public string LastId { get; } + /// A value indicating whether there are additional values available not captured in this list. + public bool? HasMore { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatchObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatchObject.cs new file mode 100644 index 000000000000..db12e107d15c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OpenAIPageableListOfBatchObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The OpenAIPageableListOfBatch_object. + public readonly partial struct OpenAIPageableListOfBatchObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OpenAIPageableListOfBatchObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ListValue = "list"; + + /// list. + public static OpenAIPageableListOfBatchObject List { get; } = new OpenAIPageableListOfBatchObject(ListValue); + /// Determines if two values are the same. + public static bool operator ==(OpenAIPageableListOfBatchObject left, OpenAIPageableListOfBatchObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OpenAIPageableListOfBatchObject left, OpenAIPageableListOfBatchObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OpenAIPageableListOfBatchObject(string value) => new OpenAIPageableListOfBatchObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OpenAIPageableListOfBatchObject other && Equals(other); + /// + public bool Equals(OpenAIPageableListOfBatchObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/OutputAudioFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/OutputAudioFormat.cs new file mode 100644 index 000000000000..dabcd0f53176 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/OutputAudioFormat.cs @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The output audio format. + public readonly partial struct OutputAudioFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public OutputAudioFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string WavValue = "wav"; + private const string Mp3Value = "mp3"; + private const string FlacValue = "flac"; + private const string OpusValue = "opus"; + private const string Pcm16Value = "pcm16"; + + /// The output audio format is WAV. + public static OutputAudioFormat Wav { get; } = new OutputAudioFormat(WavValue); + /// The output audio format is MP3. + public static OutputAudioFormat Mp3 { get; } = new OutputAudioFormat(Mp3Value); + /// The output audio format is FLAC. + public static OutputAudioFormat Flac { get; } = new OutputAudioFormat(FlacValue); + /// The output audio format is OPUS. + public static OutputAudioFormat Opus { get; } = new OutputAudioFormat(OpusValue); + /// The output audio format is PCM16. + public static OutputAudioFormat Pcm16 { get; } = new OutputAudioFormat(Pcm16Value); + /// Determines if two values are the same. + public static bool operator ==(OutputAudioFormat left, OutputAudioFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(OutputAudioFormat left, OutputAudioFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator OutputAudioFormat(string value) => new OutputAudioFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is OutputAudioFormat other && Equals(other); + /// + public bool Equals(OutputAudioFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..935f0506617d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class PineconeChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PineconeChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + writer.WritePropertyName("parameters"u8); + writer.WriteObjectValue(Parameters, options); + } + + PineconeChatExtensionConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PineconeChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePineconeChatExtensionConfiguration(document.RootElement, options); + } + + internal static PineconeChatExtensionConfiguration DeserializePineconeChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + PineconeChatExtensionParameters parameters = default; + AzureChatExtensionType type = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("parameters"u8)) + { + parameters = PineconeChatExtensionParameters.DeserializePineconeChatExtensionParameters(property.Value, options); + continue; + } + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PineconeChatExtensionConfiguration(type, serializedAdditionalRawData, parameters); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(PineconeChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + PineconeChatExtensionConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePineconeChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PineconeChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new PineconeChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePineconeChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.cs new file mode 100644 index 000000000000..047937523042 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionConfiguration.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// A specific representation of configurable options for Pinecone when using it as an Azure OpenAI chat + /// extension. + /// + public partial class PineconeChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// The parameters to use when configuring Azure OpenAI chat extensions. + /// is null. + public PineconeChatExtensionConfiguration(PineconeChatExtensionParameters parameters) + { + Argument.AssertNotNull(parameters, nameof(parameters)); + + Type = AzureChatExtensionType.Pinecone; + Parameters = parameters; + } + + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + /// The parameters to use when configuring Azure OpenAI chat extensions. + internal PineconeChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData, PineconeChatExtensionParameters parameters) : base(type, serializedAdditionalRawData) + { + Parameters = parameters; + } + + /// Initializes a new instance of for deserialization. + internal PineconeChatExtensionConfiguration() + { + } + + /// The parameters to use when configuring Azure OpenAI chat extensions. + public PineconeChatExtensionParameters Parameters { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.Serialization.cs new file mode 100644 index 000000000000..cd6463e01fc4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.Serialization.cs @@ -0,0 +1,293 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class PineconeChatExtensionParameters : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(DocumentCount)) + { + writer.WritePropertyName("top_n_documents"u8); + writer.WriteNumberValue(DocumentCount.Value); + } + if (Optional.IsDefined(ShouldRestrictResultScope)) + { + writer.WritePropertyName("in_scope"u8); + writer.WriteBooleanValue(ShouldRestrictResultScope.Value); + } + if (Optional.IsDefined(Strictness)) + { + writer.WritePropertyName("strictness"u8); + writer.WriteNumberValue(Strictness.Value); + } + if (Optional.IsDefined(MaxSearchQueries)) + { + writer.WritePropertyName("max_search_queries"u8); + writer.WriteNumberValue(MaxSearchQueries.Value); + } + if (Optional.IsDefined(AllowPartialResult)) + { + writer.WritePropertyName("allow_partial_result"u8); + writer.WriteBooleanValue(AllowPartialResult.Value); + } + if (Optional.IsCollectionDefined(IncludeContexts)) + { + writer.WritePropertyName("include_contexts"u8); + writer.WriteStartArray(); + foreach (var item in IncludeContexts) + { + writer.WriteStringValue(item.ToString()); + } + writer.WriteEndArray(); + } + if (Optional.IsDefined(Authentication)) + { + writer.WritePropertyName("authentication"u8); + writer.WriteObjectValue(Authentication, options); + } + writer.WritePropertyName("environment"u8); + writer.WriteStringValue(EnvironmentName); + writer.WritePropertyName("index_name"u8); + writer.WriteStringValue(IndexName); + writer.WritePropertyName("fields_mapping"u8); + writer.WriteObjectValue(FieldMappingOptions, options); + writer.WritePropertyName("embedding_dependency"u8); + writer.WriteObjectValue(EmbeddingDependency, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + PineconeChatExtensionParameters IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePineconeChatExtensionParameters(document.RootElement, options); + } + + internal static PineconeChatExtensionParameters DeserializePineconeChatExtensionParameters(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + int? topNDocuments = default; + bool? inScope = default; + int? strictness = default; + int? maxSearchQueries = default; + bool? allowPartialResult = default; + IList includeContexts = default; + OnYourDataAuthenticationOptions authentication = default; + string environment = default; + string indexName = default; + PineconeFieldMappingOptions fieldsMapping = default; + OnYourDataVectorizationSource embeddingDependency = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("top_n_documents"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + topNDocuments = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("in_scope"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + inScope = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("strictness"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + strictness = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("max_search_queries"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxSearchQueries = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("allow_partial_result"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + allowPartialResult = property.Value.GetBoolean(); + continue; + } + if (property.NameEquals("include_contexts"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(new OnYourDataContextProperty(item.GetString())); + } + includeContexts = array; + continue; + } + if (property.NameEquals("authentication"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + authentication = OnYourDataAuthenticationOptions.DeserializeOnYourDataAuthenticationOptions(property.Value, options); + continue; + } + if (property.NameEquals("environment"u8)) + { + environment = property.Value.GetString(); + continue; + } + if (property.NameEquals("index_name"u8)) + { + indexName = property.Value.GetString(); + continue; + } + if (property.NameEquals("fields_mapping"u8)) + { + fieldsMapping = PineconeFieldMappingOptions.DeserializePineconeFieldMappingOptions(property.Value, options); + continue; + } + if (property.NameEquals("embedding_dependency"u8)) + { + embeddingDependency = OnYourDataVectorizationSource.DeserializeOnYourDataVectorizationSource(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PineconeChatExtensionParameters( + topNDocuments, + inScope, + strictness, + maxSearchQueries, + allowPartialResult, + includeContexts ?? new ChangeTrackingList(), + authentication, + environment, + indexName, + fieldsMapping, + embeddingDependency, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support writing '{options.Format}' format."); + } + } + + PineconeChatExtensionParameters IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePineconeChatExtensionParameters(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PineconeChatExtensionParameters)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static PineconeChatExtensionParameters FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePineconeChatExtensionParameters(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.cs new file mode 100644 index 000000000000..7f1a38f68a42 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeChatExtensionParameters.cs @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Parameters for configuring Azure OpenAI Pinecone chat extensions. The supported authentication type is APIKey. + public partial class PineconeChatExtensionParameters + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The environment name of Pinecone. + /// The name of the Pinecone database index. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// , , or is null. + public PineconeChatExtensionParameters(string environmentName, string indexName, PineconeFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency) + { + Argument.AssertNotNull(environmentName, nameof(environmentName)); + Argument.AssertNotNull(indexName, nameof(indexName)); + Argument.AssertNotNull(fieldMappingOptions, nameof(fieldMappingOptions)); + Argument.AssertNotNull(embeddingDependency, nameof(embeddingDependency)); + + IncludeContexts = new ChangeTrackingList(); + EnvironmentName = environmentName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + } + + /// Initializes a new instance of . + /// The configured top number of documents to feature for the configured query. + /// Whether queries should be restricted to use of indexed data. + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + /// The environment name of Pinecone. + /// The name of the Pinecone database index. + /// Customized field mapping behavior to use when interacting with the search index. + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + /// Keeps track of any properties unknown to the library. + internal PineconeChatExtensionParameters(int? documentCount, bool? shouldRestrictResultScope, int? strictness, int? maxSearchQueries, bool? allowPartialResult, IList includeContexts, OnYourDataAuthenticationOptions authentication, string environmentName, string indexName, PineconeFieldMappingOptions fieldMappingOptions, OnYourDataVectorizationSource embeddingDependency, IDictionary serializedAdditionalRawData) + { + DocumentCount = documentCount; + ShouldRestrictResultScope = shouldRestrictResultScope; + Strictness = strictness; + MaxSearchQueries = maxSearchQueries; + AllowPartialResult = allowPartialResult; + IncludeContexts = includeContexts; + Authentication = authentication; + EnvironmentName = environmentName; + IndexName = indexName; + FieldMappingOptions = fieldMappingOptions; + EmbeddingDependency = embeddingDependency; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal PineconeChatExtensionParameters() + { + } + + /// The configured top number of documents to feature for the configured query. + public int? DocumentCount { get; set; } + /// Whether queries should be restricted to use of indexed data. + public bool? ShouldRestrictResultScope { get; set; } + /// The configured strictness of the search relevance filtering. The higher of strictness, the higher of the precision but lower recall of the answer. + public int? Strictness { get; set; } + /// + /// The max number of rewritten queries should be send to search provider for one user message. If not specified, + /// the system will decide the number of queries to send. + /// + public int? MaxSearchQueries { get; set; } + /// + /// If specified as true, the system will allow partial search results to be used and the request fails if all the queries fail. + /// If not specified, or specified as false, the request will fail if any search query fails. + /// + public bool? AllowPartialResult { get; set; } + /// The included properties of the output context. If not specified, the default value is `citations` and `intent`. + public IList IncludeContexts { get; } + /// + /// 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. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , , , , , and . + /// + public OnYourDataAuthenticationOptions Authentication { get; set; } + /// The environment name of Pinecone. + public string EnvironmentName { get; } + /// The name of the Pinecone database index. + public string IndexName { get; } + /// Customized field mapping behavior to use when interacting with the search index. + public PineconeFieldMappingOptions FieldMappingOptions { get; } + /// + /// The embedding dependency for vector search. + /// Please note is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes. + /// The available derived classes include , , and . + /// + public OnYourDataVectorizationSource EmbeddingDependency { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.Serialization.cs new file mode 100644 index 000000000000..4eb073c2e725 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.Serialization.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class PineconeFieldMappingOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PineconeFieldMappingOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(TitleFieldName)) + { + writer.WritePropertyName("title_field"u8); + writer.WriteStringValue(TitleFieldName); + } + if (Optional.IsDefined(UrlFieldName)) + { + writer.WritePropertyName("url_field"u8); + writer.WriteStringValue(UrlFieldName); + } + if (Optional.IsDefined(FilepathFieldName)) + { + writer.WritePropertyName("filepath_field"u8); + writer.WriteStringValue(FilepathFieldName); + } + writer.WritePropertyName("content_fields"u8); + writer.WriteStartArray(); + foreach (var item in ContentFieldNames) + { + writer.WriteStringValue(item); + } + writer.WriteEndArray(); + if (Optional.IsDefined(ContentFieldSeparator)) + { + writer.WritePropertyName("content_fields_separator"u8); + writer.WriteStringValue(ContentFieldSeparator); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + PineconeFieldMappingOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PineconeFieldMappingOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePineconeFieldMappingOptions(document.RootElement, options); + } + + internal static PineconeFieldMappingOptions DeserializePineconeFieldMappingOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string titleField = default; + string urlField = default; + string filepathField = default; + IList contentFields = default; + string contentFieldsSeparator = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("title_field"u8)) + { + titleField = property.Value.GetString(); + continue; + } + if (property.NameEquals("url_field"u8)) + { + urlField = property.Value.GetString(); + continue; + } + if (property.NameEquals("filepath_field"u8)) + { + filepathField = property.Value.GetString(); + continue; + } + if (property.NameEquals("content_fields"u8)) + { + List array = new List(); + foreach (var item in property.Value.EnumerateArray()) + { + array.Add(item.GetString()); + } + contentFields = array; + continue; + } + if (property.NameEquals("content_fields_separator"u8)) + { + contentFieldsSeparator = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PineconeFieldMappingOptions( + titleField, + urlField, + filepathField, + contentFields, + contentFieldsSeparator, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(PineconeFieldMappingOptions)} does not support writing '{options.Format}' format."); + } + } + + PineconeFieldMappingOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePineconeFieldMappingOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PineconeFieldMappingOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static PineconeFieldMappingOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePineconeFieldMappingOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.cs new file mode 100644 index 000000000000..4d3d569a6533 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PineconeFieldMappingOptions.cs @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.AI.OpenAI +{ + /// Optional settings to control how fields are processed when using a configured Pinecone resource. + public partial class PineconeFieldMappingOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The names of index fields that should be treated as content. + /// is null. + public PineconeFieldMappingOptions(IEnumerable contentFieldNames) + { + Argument.AssertNotNull(contentFieldNames, nameof(contentFieldNames)); + + ContentFieldNames = contentFieldNames.ToList(); + } + + /// Initializes a new instance of . + /// The name of the index field to use as a title. + /// The name of the index field to use as a URL. + /// The name of the index field to use as a filepath. + /// The names of index fields that should be treated as content. + /// The separator pattern that content fields should use. + /// Keeps track of any properties unknown to the library. + internal PineconeFieldMappingOptions(string titleFieldName, string urlFieldName, string filepathFieldName, IList contentFieldNames, string contentFieldSeparator, IDictionary serializedAdditionalRawData) + { + TitleFieldName = titleFieldName; + UrlFieldName = urlFieldName; + FilepathFieldName = filepathFieldName; + ContentFieldNames = contentFieldNames; + ContentFieldSeparator = contentFieldSeparator; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal PineconeFieldMappingOptions() + { + } + + /// The name of the index field to use as a title. + public string TitleFieldName { get; set; } + /// The name of the index field to use as a URL. + public string UrlFieldName { get; set; } + /// The name of the index field to use as a filepath. + public string FilepathFieldName { get; set; } + /// The names of index fields that should be treated as content. + public IList ContentFieldNames { get; } + /// The separator pattern that content fields should use. + public string ContentFieldSeparator { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.Serialization.cs new file mode 100644 index 000000000000..5357ca173ab7 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.Serialization.cs @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class PredictionContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PredictionContent)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("type"u8); + writer.WriteStringValue(Type.ToString()); + writer.WritePropertyName("content"u8); +#if NET6_0_OR_GREATER + writer.WriteRawValue(Content); +#else + using (JsonDocument document = JsonDocument.Parse(Content, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + PredictionContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(PredictionContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializePredictionContent(document.RootElement, options); + } + + internal static PredictionContent DeserializePredictionContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + PredictionContentType type = default; + BinaryData content = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new PredictionContentType(property.Value.GetString()); + continue; + } + if (property.NameEquals("content"u8)) + { + content = BinaryData.FromString(property.Value.GetRawText()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new PredictionContent(type, content, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(PredictionContent)} does not support writing '{options.Format}' format."); + } + } + + PredictionContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePredictionContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(PredictionContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static PredictionContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializePredictionContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.cs new file mode 100644 index 000000000000..967cb6036c51 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContent.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Static predicted output content, such as the content of a text file that is being regenerated. + public partial class PredictionContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// + /// The content that should be matched when generating a model response. + /// If generated tokens would match this content, the entire model response + /// can be returned much more quickly. + /// + /// is null. + public PredictionContent(BinaryData content) + { + Argument.AssertNotNull(content, nameof(content)); + + Content = content; + } + + /// Initializes a new instance of . + /// + /// The type of the predicted content you want to provide. This type is + /// currently always `content`. + /// + /// + /// The content that should be matched when generating a model response. + /// If generated tokens would match this content, the entire model response + /// can be returned much more quickly. + /// + /// Keeps track of any properties unknown to the library. + internal PredictionContent(PredictionContentType type, BinaryData content, IDictionary serializedAdditionalRawData) + { + Type = type; + Content = content; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal PredictionContent() + { + } + + /// + /// The type of the predicted content you want to provide. This type is + /// currently always `content`. + /// + public PredictionContentType Type { get; } = PredictionContentType.Content; + + /// + /// The content that should be matched when generating a model response. + /// If generated tokens would match this content, the entire model response + /// can be returned much more quickly. + /// + /// To assign an object to this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// + /// Supported types: + /// + /// + /// + /// + /// + /// where T is of type + /// + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + public BinaryData Content { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContentType.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContentType.cs new file mode 100644 index 000000000000..83d4b6d0c72a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/PredictionContentType.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The types of predicted content. + public readonly partial struct PredictionContentType : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public PredictionContentType(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string ContentValue = "content"; + + /// Predicted content is of type content. + public static PredictionContentType Content { get; } = new PredictionContentType(ContentValue); + /// Determines if two values are the same. + public static bool operator ==(PredictionContentType left, PredictionContentType right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(PredictionContentType left, PredictionContentType right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator PredictionContentType(string value) => new PredictionContentType(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is PredictionContentType other && Equals(other); + /// + public bool Equals(PredictionContentType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/ReasoningEffortValue.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/ReasoningEffortValue.cs new file mode 100644 index 000000000000..3d8ba4c1b0ef --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/ReasoningEffortValue.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// Values for the reasoning. + public readonly partial struct ReasoningEffortValue : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public ReasoningEffortValue(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string LowValue = "low"; + private const string MediumValue = "medium"; + private const string HighValue = "high"; + + /// The reasoning effort is low. + public static ReasoningEffortValue Low { get; } = new ReasoningEffortValue(LowValue); + /// The reasoning effort is medium. + public static ReasoningEffortValue Medium { get; } = new ReasoningEffortValue(MediumValue); + /// The reasoning effort is high. + public static ReasoningEffortValue High { get; } = new ReasoningEffortValue(HighValue); + /// Determines if two values are the same. + public static bool operator ==(ReasoningEffortValue left, ReasoningEffortValue right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(ReasoningEffortValue left, ReasoningEffortValue right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator ReasoningEffortValue(string value) => new ReasoningEffortValue(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is ReasoningEffortValue other && Equals(other); + /// + public bool Equals(ReasoningEffortValue other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.Serialization.cs new file mode 100644 index 000000000000..d287cd56404a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.Serialization.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class SpeechGenerationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SpeechGenerationOptions)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("input"u8); + writer.WriteStringValue(Input); + writer.WritePropertyName("voice"u8); + writer.WriteStringValue(Voice.ToString()); + if (Optional.IsDefined(ResponseFormat)) + { + writer.WritePropertyName("response_format"u8); + writer.WriteStringValue(ResponseFormat.Value.ToString()); + } + if (Optional.IsDefined(Speed)) + { + writer.WritePropertyName("speed"u8); + writer.WriteNumberValue(Speed.Value); + } + if (Optional.IsDefined(DeploymentName)) + { + writer.WritePropertyName("model"u8); + writer.WriteStringValue(DeploymentName); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SpeechGenerationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SpeechGenerationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSpeechGenerationOptions(document.RootElement, options); + } + + internal static SpeechGenerationOptions DeserializeSpeechGenerationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string input = default; + SpeechVoice voice = default; + SpeechGenerationResponseFormat? responseFormat = default; + float? speed = default; + string model = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("input"u8)) + { + input = property.Value.GetString(); + continue; + } + if (property.NameEquals("voice"u8)) + { + voice = new SpeechVoice(property.Value.GetString()); + continue; + } + if (property.NameEquals("response_format"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + responseFormat = new SpeechGenerationResponseFormat(property.Value.GetString()); + continue; + } + if (property.NameEquals("speed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + speed = property.Value.GetSingle(); + continue; + } + if (property.NameEquals("model"u8)) + { + model = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SpeechGenerationOptions( + input, + voice, + responseFormat, + speed, + model, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SpeechGenerationOptions)} does not support writing '{options.Format}' format."); + } + } + + SpeechGenerationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSpeechGenerationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SpeechGenerationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SpeechGenerationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSpeechGenerationOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.cs new file mode 100644 index 000000000000..21f6b6fd2888 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationOptions.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// A representation of the request options that control the behavior of a text-to-speech operation. + public partial class SpeechGenerationOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The text to generate audio for. The maximum length is 4096 characters. + /// The voice to use for text-to-speech. + /// is null. + public SpeechGenerationOptions(string input, SpeechVoice voice) + { + Argument.AssertNotNull(input, nameof(input)); + + Input = input; + Voice = voice; + } + + /// Initializes a new instance of . + /// The text to generate audio for. The maximum length is 4096 characters. + /// The voice to use for text-to-speech. + /// The audio output format for the spoken text. By default, the MP3 format will be used. + /// The speed of speech for generated audio. Values are valid in the range from 0.25 to 4.0, with 1.0 the default and higher values corresponding to faster speech. + /// The model to use for this text-to-speech request. + /// Keeps track of any properties unknown to the library. + internal SpeechGenerationOptions(string input, SpeechVoice voice, SpeechGenerationResponseFormat? responseFormat, float? speed, string deploymentName, IDictionary serializedAdditionalRawData) + { + Input = input; + Voice = voice; + ResponseFormat = responseFormat; + Speed = speed; + DeploymentName = deploymentName; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SpeechGenerationOptions() + { + } + + /// The text to generate audio for. The maximum length is 4096 characters. + public string Input { get; } + /// The voice to use for text-to-speech. + public SpeechVoice Voice { get; } + /// The audio output format for the spoken text. By default, the MP3 format will be used. + public SpeechGenerationResponseFormat? ResponseFormat { get; set; } + /// The speed of speech for generated audio. Values are valid in the range from 0.25 to 4.0, with 1.0 the default and higher values corresponding to faster speech. + public float? Speed { get; set; } + /// The model to use for this text-to-speech request. + public string DeploymentName { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationResponseFormat.cs new file mode 100644 index 000000000000..e2af864d093b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechGenerationResponseFormat.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The supported audio output formats for text-to-speech. + public readonly partial struct SpeechGenerationResponseFormat : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SpeechGenerationResponseFormat(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string Mp3Value = "mp3"; + private const string OpusValue = "opus"; + private const string AacValue = "aac"; + private const string FlacValue = "flac"; + private const string WavValue = "wav"; + private const string PcmValue = "pcm"; + + /// Use MP3 as the audio output format. MP3 is the default, general-purpose format. + public static SpeechGenerationResponseFormat Mp3 { get; } = new SpeechGenerationResponseFormat(Mp3Value); + /// Use Opus as the audio output format. Opus is optimized for internet streaming and low latency. + public static SpeechGenerationResponseFormat Opus { get; } = new SpeechGenerationResponseFormat(OpusValue); + /// Use AAC as the audio output format. AAC is optimized for digital audio compression and is preferred by YouTube, Android, and iOS. + public static SpeechGenerationResponseFormat Aac { get; } = new SpeechGenerationResponseFormat(AacValue); + /// Use FLAC as the audio output format. FLAC is a fully lossless format optimized for maximum quality at the expense of size. + public static SpeechGenerationResponseFormat Flac { get; } = new SpeechGenerationResponseFormat(FlacValue); + /// Use uncompressed WAV as the audio output format, suitable for low-latency applications to avoid decoding overhead. + public static SpeechGenerationResponseFormat Wav { get; } = new SpeechGenerationResponseFormat(WavValue); + /// Use uncompressed PCM as the audio output format, which is similar to WAV but contains raw samples in 24kHz (16-bit signed, low-endian), without the header. + public static SpeechGenerationResponseFormat Pcm { get; } = new SpeechGenerationResponseFormat(PcmValue); + /// Determines if two values are the same. + public static bool operator ==(SpeechGenerationResponseFormat left, SpeechGenerationResponseFormat right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SpeechGenerationResponseFormat left, SpeechGenerationResponseFormat right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator SpeechGenerationResponseFormat(string value) => new SpeechGenerationResponseFormat(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SpeechGenerationResponseFormat other && Equals(other); + /// + public bool Equals(SpeechGenerationResponseFormat other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechVoice.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechVoice.cs new file mode 100644 index 000000000000..a4b9c07a167f --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/SpeechVoice.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The available voices for text-to-speech. + public readonly partial struct SpeechVoice : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public SpeechVoice(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string AlloyValue = "alloy"; + private const string EchoValue = "echo"; + private const string FableValue = "fable"; + private const string OnyxValue = "onyx"; + private const string NovaValue = "nova"; + private const string ShimmerValue = "shimmer"; + + /// The Alloy voice. + public static SpeechVoice Alloy { get; } = new SpeechVoice(AlloyValue); + /// The Echo voice. + public static SpeechVoice Echo { get; } = new SpeechVoice(EchoValue); + /// The Fable voice. + public static SpeechVoice Fable { get; } = new SpeechVoice(FableValue); + /// The Onyx voice. + public static SpeechVoice Onyx { get; } = new SpeechVoice(OnyxValue); + /// The Nova voice. + public static SpeechVoice Nova { get; } = new SpeechVoice(NovaValue); + /// The Shimmer voice. + public static SpeechVoice Shimmer { get; } = new SpeechVoice(ShimmerValue); + /// Determines if two values are the same. + public static bool operator ==(SpeechVoice left, SpeechVoice right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(SpeechVoice left, SpeechVoice right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator SpeechVoice(string value) => new SpeechVoice(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is SpeechVoice other && Equals(other); + /// + public bool Equals(SpeechVoice other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.Serialization.cs new file mode 100644 index 000000000000..6106413103ff --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownAzureChatExtensionConfiguration : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + AzureChatExtensionConfiguration IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + + internal static UnknownAzureChatExtensionConfiguration DeserializeUnknownAzureChatExtensionConfiguration(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + AzureChatExtensionType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new AzureChatExtensionType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownAzureChatExtensionConfiguration(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support writing '{options.Format}' format."); + } + } + + AzureChatExtensionConfiguration IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeAzureChatExtensionConfiguration(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(AzureChatExtensionConfiguration)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownAzureChatExtensionConfiguration FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownAzureChatExtensionConfiguration(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.cs new file mode 100644 index 000000000000..c9f09702aa3a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownAzureChatExtensionConfiguration.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of AzureChatExtensionConfiguration. + internal partial class UnknownAzureChatExtensionConfiguration : AzureChatExtensionConfiguration + { + /// Initializes a new instance of . + /// + /// The label for the type of an Azure chat extension. This typically corresponds to a matching Azure resource. + /// Azure chat extensions are only compatible with Azure OpenAI. + /// + /// Keeps track of any properties unknown to the library. + internal UnknownAzureChatExtensionConfiguration(AzureChatExtensionType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownAzureChatExtensionConfiguration() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.Serialization.cs new file mode 100644 index 000000000000..2a6127d5fde3 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatCompletionsNamedToolSelection : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ChatCompletionsNamedToolSelection IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + + internal static UnknownChatCompletionsNamedToolSelection DeserializeUnknownChatCompletionsNamedToolSelection(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatCompletionsNamedToolSelection(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsNamedToolSelection IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsNamedToolSelection(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsNamedToolSelection)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatCompletionsNamedToolSelection FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownChatCompletionsNamedToolSelection(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.cs new file mode 100644 index 000000000000..f3a885278854 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsNamedToolSelection.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsNamedToolSelection. + internal partial class UnknownChatCompletionsNamedToolSelection : ChatCompletionsNamedToolSelection + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsNamedToolSelection(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsNamedToolSelection() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.Serialization.cs new file mode 100644 index 000000000000..c352cdc67ee0 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatCompletionsResponseFormat : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ChatCompletionsResponseFormat IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + + internal static UnknownChatCompletionsResponseFormat DeserializeUnknownChatCompletionsResponseFormat(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatCompletionsResponseFormat(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsResponseFormat IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsResponseFormat(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsResponseFormat)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatCompletionsResponseFormat FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownChatCompletionsResponseFormat(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.cs new file mode 100644 index 000000000000..1b7ad649a682 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsResponseFormat.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsResponseFormat. + internal partial class UnknownChatCompletionsResponseFormat : ChatCompletionsResponseFormat + { + /// Initializes a new instance of . + /// The discriminated type for the response format. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsResponseFormat(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsResponseFormat() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.Serialization.cs similarity index 62% rename from sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.Serialization.cs index c706bdbf9bab..2eabfb2229b0 100644 --- a/sdk/openai/Azure.AI.OpenAI.Assistants/src/Generated/RetrievalToolDefinition.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.Serialization.cs @@ -11,13 +11,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.OpenAI.Assistants +namespace Azure.AI.OpenAI { - public partial class RetrievalToolDefinition : IUtf8JsonSerializable, IJsonModel + internal partial class UnknownChatCompletionsToolCall : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -28,28 +28,28 @@ void IJsonModel.Write(Utf8JsonWriter writer, ModelReade /// The client options for reading and writing models. protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(RetrievalToolDefinition)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support writing '{format}' format."); } base.JsonModelWriteCore(writer, options); } - RetrievalToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + ChatCompletionsToolCall IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(RetrievalToolDefinition)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeRetrievalToolDefinition(document.RootElement, options); + return DeserializeChatCompletionsToolCall(document.RootElement, options); } - internal static RetrievalToolDefinition DeserializeRetrievalToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + internal static UnknownChatCompletionsToolCall DeserializeUnknownChatCompletionsToolCall(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -57,7 +57,8 @@ internal static RetrievalToolDefinition DeserializeRetrievalToolDefinition(JsonE { return null; } - string type = default; + string type = "Unknown"; + string id = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -67,59 +68,64 @@ internal static RetrievalToolDefinition DeserializeRetrievalToolDefinition(JsonE type = property.Value.GetString(); continue; } + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new RetrievalToolDefinition(type, serializedAdditionalRawData); + return new UnknownChatCompletionsToolCall(type, id, serializedAdditionalRawData); } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": return ModelReaderWriter.Write(this, options); default: - throw new FormatException($"The model {nameof(RetrievalToolDefinition)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support writing '{options.Format}' format."); } } - RetrievalToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + ChatCompletionsToolCall IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeRetrievalToolDefinition(document.RootElement, options); + return DeserializeChatCompletionsToolCall(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(RetrievalToolDefinition)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(ChatCompletionsToolCall)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static new RetrievalToolDefinition FromResponse(Response response) + internal static new UnknownChatCompletionsToolCall FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeRetrievalToolDefinition(document.RootElement); + return DeserializeUnknownChatCompletionsToolCall(document.RootElement); } /// Convert into a . internal override RequestContent ToRequestContent() { var content = new Utf8JsonRequestContent(); - content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); return content; } } diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.cs new file mode 100644 index 000000000000..88be20fa0524 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolCall.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsToolCall. + internal partial class UnknownChatCompletionsToolCall : ChatCompletionsToolCall + { + /// Initializes a new instance of . + /// The object type. + /// The ID of the tool call. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsToolCall(string type, string id, IDictionary serializedAdditionalRawData) : base(type, id, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsToolCall() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.Serialization.cs new file mode 100644 index 000000000000..8bcab1c25aac --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatCompletionsToolDefinition : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ChatCompletionsToolDefinition IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + + internal static UnknownChatCompletionsToolDefinition DeserializeUnknownChatCompletionsToolDefinition(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatCompletionsToolDefinition(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support writing '{options.Format}' format."); + } + } + + ChatCompletionsToolDefinition IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatCompletionsToolDefinition(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatCompletionsToolDefinition)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatCompletionsToolDefinition FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownChatCompletionsToolDefinition(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.cs new file mode 100644 index 000000000000..5b671919dd47 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatCompletionsToolDefinition.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatCompletionsToolDefinition. + internal partial class UnknownChatCompletionsToolDefinition : ChatCompletionsToolDefinition + { + /// Initializes a new instance of . + /// The object type. + /// Keeps track of any properties unknown to the library. + internal UnknownChatCompletionsToolDefinition(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatCompletionsToolDefinition() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.Serialization.cs new file mode 100644 index 000000000000..ea8a94d30b88 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatMessageContentItem : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ChatMessageContentItem IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatMessageContentItem(document.RootElement, options); + } + + internal static UnknownChatMessageContentItem DeserializeUnknownChatMessageContentItem(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatMessageContentItem(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support writing '{options.Format}' format."); + } + } + + ChatMessageContentItem IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatMessageContentItem(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatMessageContentItem)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatMessageContentItem FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownChatMessageContentItem(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.cs new file mode 100644 index 000000000000..7407e7520c34 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatMessageContentItem.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatMessageContentItem. + internal partial class UnknownChatMessageContentItem : ChatMessageContentItem + { + /// Initializes a new instance of . + /// The discriminated object type. + /// Keeps track of any properties unknown to the library. + internal UnknownChatMessageContentItem(string type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatMessageContentItem() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.Serialization.cs new file mode 100644 index 000000000000..72509c299307 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownChatRequestMessage : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + ChatRequestMessage IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeChatRequestMessage(document.RootElement, options); + } + + internal static UnknownChatRequestMessage DeserializeUnknownChatRequestMessage(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + ChatRole role = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("role"u8)) + { + role = new ChatRole(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownChatRequestMessage(role, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support writing '{options.Format}' format."); + } + } + + ChatRequestMessage IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeChatRequestMessage(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(ChatRequestMessage)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownChatRequestMessage FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownChatRequestMessage(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.cs new file mode 100644 index 000000000000..16ce3943613b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownChatRequestMessage.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of ChatRequestMessage. + internal partial class UnknownChatRequestMessage : ChatRequestMessage + { + /// Initializes a new instance of . + /// The chat role associated with this message. + /// Keeps track of any properties unknown to the library. + internal UnknownChatRequestMessage(ChatRole role, IDictionary serializedAdditionalRawData) : base(role, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownChatRequestMessage() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..66acd465fd30 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownOnYourDataAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + OnYourDataAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + + internal static UnknownOnYourDataAuthenticationOptions DeserializeUnknownOnYourDataAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataAuthenticationType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownOnYourDataAuthenticationOptions(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownOnYourDataAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownOnYourDataAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.cs new file mode 100644 index 000000000000..3d47c4f32f51 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataAuthenticationOptions.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of OnYourDataAuthenticationOptions. + internal partial class UnknownOnYourDataAuthenticationOptions : OnYourDataAuthenticationOptions + { + /// Initializes a new instance of . + /// The authentication type. + /// Keeps track of any properties unknown to the library. + internal UnknownOnYourDataAuthenticationOptions(OnYourDataAuthenticationType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownOnYourDataAuthenticationOptions() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.Serialization.cs new file mode 100644 index 000000000000..c8d6230c15b6 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownOnYourDataVectorSearchAuthenticationOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + OnYourDataVectorSearchAuthenticationOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + + internal static UnknownOnYourDataVectorSearchAuthenticationOptions DeserializeUnknownOnYourDataVectorSearchAuthenticationOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataVectorSearchAuthenticationType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorSearchAuthenticationType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownOnYourDataVectorSearchAuthenticationOptions(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorSearchAuthenticationOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorSearchAuthenticationOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorSearchAuthenticationOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownOnYourDataVectorSearchAuthenticationOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownOnYourDataVectorSearchAuthenticationOptions(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.cs new file mode 100644 index 000000000000..13d87a07efb2 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorSearchAuthenticationOptions.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of OnYourDataVectorSearchAuthenticationOptions. + internal partial class UnknownOnYourDataVectorSearchAuthenticationOptions : OnYourDataVectorSearchAuthenticationOptions + { + /// Initializes a new instance of . + /// The type of authentication to use. + /// Keeps track of any properties unknown to the library. + internal UnknownOnYourDataVectorSearchAuthenticationOptions(OnYourDataVectorSearchAuthenticationType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownOnYourDataVectorSearchAuthenticationOptions() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.Serialization.cs new file mode 100644 index 000000000000..e1f3eb579fc5 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.Serialization.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + internal partial class UnknownOnYourDataVectorizationSource : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support writing '{format}' format."); + } + + base.JsonModelWriteCore(writer, options); + } + + OnYourDataVectorizationSource IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + + internal static UnknownOnYourDataVectorizationSource DeserializeUnknownOnYourDataVectorizationSource(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + OnYourDataVectorizationSourceType type = "Unknown"; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("type"u8)) + { + type = new OnYourDataVectorizationSourceType(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UnknownOnYourDataVectorizationSource(type, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support writing '{options.Format}' format."); + } + } + + OnYourDataVectorizationSource IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeOnYourDataVectorizationSource(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(OnYourDataVectorizationSource)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static new UnknownOnYourDataVectorizationSource FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUnknownOnYourDataVectorizationSource(document.RootElement); + } + + /// Convert into a . + internal override RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.cs new file mode 100644 index 000000000000..2bf5702ab3fd --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UnknownOnYourDataVectorizationSource.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// Unknown version of OnYourDataVectorizationSource. + internal partial class UnknownOnYourDataVectorizationSource : OnYourDataVectorizationSource + { + /// Initializes a new instance of . + /// The type of vectorization source to use. + /// Keeps track of any properties unknown to the library. + internal UnknownOnYourDataVectorizationSource(OnYourDataVectorizationSourceType type, IDictionary serializedAdditionalRawData) : base(type, serializedAdditionalRawData) + { + } + + /// Initializes a new instance of for deserialization. + internal UnknownOnYourDataVectorizationSource() + { + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.Serialization.cs new file mode 100644 index 000000000000..8d5c6e8fd64a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.Serialization.cs @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class Upload : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Upload)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + writer.WritePropertyName("bytes"u8); + writer.WriteNumberValue(Bytes); + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + writer.WritePropertyName("status"u8); + writer.WriteStringValue(Status.ToString()); + writer.WritePropertyName("expires_at"u8); + writer.WriteNumberValue(ExpiresAt, "U"); + if (Optional.IsDefined(Object)) + { + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.Value.ToString()); + } + if (Optional.IsDefined(File)) + { + if (File != null) + { + writer.WritePropertyName("file"u8); + writer.WriteObjectValue(File, options); + } + else + { + writer.WriteNull("file"); + } + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Upload IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Upload)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUpload(document.RootElement, options); + } + + internal static Upload DeserializeUpload(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset createdAt = default; + string filename = default; + long bytes = default; + UploadPurpose purpose = default; + UploadStatus status = default; + DateTimeOffset expiresAt = default; + UploadObject? @object = default; + OpenAIFile file = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); + continue; + } + if (property.NameEquals("bytes"u8)) + { + bytes = property.Value.GetInt64(); + continue; + } + if (property.NameEquals("purpose"u8)) + { + purpose = new UploadPurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("status"u8)) + { + status = new UploadStatus(property.Value.GetString()); + continue; + } + if (property.NameEquals("expires_at"u8)) + { + expiresAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("object"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + @object = new UploadObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("file"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + file = null; + continue; + } + file = OpenAIFile.DeserializeOpenAIFile(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Upload( + id, + createdAt, + filename, + bytes, + purpose, + status, + expiresAt, + @object, + file, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Upload)} does not support writing '{options.Format}' format."); + } + } + + Upload IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpload(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Upload)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Upload FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUpload(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.cs new file mode 100644 index 000000000000..ac29382c966a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/Upload.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The Upload object can accept byte chunks in the form of Parts. + public partial class Upload + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The Upload unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The name of the file to be uploaded. + /// The intended number of bytes to be uploaded. + /// The intended purpose of the file. + /// The status of the Upload. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// or is null. + internal Upload(string id, DateTimeOffset createdAt, string filename, long bytes, UploadPurpose purpose, UploadStatus status, DateTimeOffset expiresAt) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(filename, nameof(filename)); + + Id = id; + CreatedAt = createdAt; + Filename = filename; + Bytes = bytes; + Purpose = purpose; + Status = status; + ExpiresAt = expiresAt; + } + + /// Initializes a new instance of . + /// The Upload unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The name of the file to be uploaded. + /// The intended number of bytes to be uploaded. + /// The intended purpose of the file. + /// The status of the Upload. + /// The Unix timestamp (in seconds) for when the Upload was created. + /// The object type, which is always "upload". + /// The ready File object after the Upload is completed. + /// Keeps track of any properties unknown to the library. + internal Upload(string id, DateTimeOffset createdAt, string filename, long bytes, UploadPurpose purpose, UploadStatus status, DateTimeOffset expiresAt, UploadObject? @object, OpenAIFile file, IDictionary serializedAdditionalRawData) + { + Id = id; + CreatedAt = createdAt; + Filename = filename; + Bytes = bytes; + Purpose = purpose; + Status = status; + ExpiresAt = expiresAt; + Object = @object; + File = file; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Upload() + { + } + + /// The Upload unique identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The Unix timestamp (in seconds) for when the Upload was created. + public DateTimeOffset CreatedAt { get; } + /// The name of the file to be uploaded. + public string Filename { get; } + /// The intended number of bytes to be uploaded. + public long Bytes { get; } + /// The intended purpose of the file. + public UploadPurpose Purpose { get; } + /// The status of the Upload. + public UploadStatus Status { get; } + /// The Unix timestamp (in seconds) for when the Upload was created. + public DateTimeOffset ExpiresAt { get; } + /// The object type, which is always "upload". + public UploadObject? Object { get; } + /// The ready File object after the Upload is completed. + public OpenAIFile File { get; } + } +} diff --git a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.Serialization.cs similarity index 56% rename from sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.Serialization.cs rename to sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.Serialization.cs index edc3e7532592..afb84a23baee 100644 --- a/sdk/face/Azure.AI.Vision.Face/src/Generated/CreateLivenessWithVerifySessionMultipartContent.Serialization.cs +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.Serialization.cs @@ -12,13 +12,13 @@ using System.Text.Json; using Azure.Core; -namespace Azure.AI.Vision.Face +namespace Azure.AI.OpenAI { - internal partial class CreateLivenessWithVerifySessionMultipartContent : IUtf8JsonSerializable, IJsonModel + public partial class UploadFileRequest : IUtf8JsonSerializable, IJsonModel { - void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); - void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) { writer.WriteStartObject(); JsonModelWriteCore(writer, options); @@ -29,23 +29,28 @@ void IJsonModel.Write(Utf8JsonW /// The client options for reading and writing models. protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support writing '{format}' format."); + throw new FormatException($"The model {nameof(UploadFileRequest)} does not support writing '{format}' format."); } - writer.WritePropertyName("Parameters"u8); - writer.WriteObjectValue(Parameters, options); - writer.WritePropertyName("VerifyImage"u8); + writer.WritePropertyName("file"u8); #if NET6_0_OR_GREATER - writer.WriteRawValue(global::System.BinaryData.FromStream(VerifyImage)); + writer.WriteRawValue(global::System.BinaryData.FromStream(Data)); #else - using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(VerifyImage), ModelSerializationExtensions.JsonDocumentOptions)) + using (JsonDocument document = JsonDocument.Parse(BinaryData.FromStream(Data), ModelSerializationExtensions.JsonDocumentOptions)) { JsonSerializer.Serialize(writer, document.RootElement); } #endif + writer.WritePropertyName("purpose"u8); + writer.WriteStringValue(Purpose.ToString()); + if (Optional.IsDefined(Filename)) + { + writer.WritePropertyName("filename"u8); + writer.WriteStringValue(Filename); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -63,19 +68,19 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } } - CreateLivenessWithVerifySessionMultipartContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + UploadFileRequest IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; if (format != "J") { - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support reading '{format}' format."); + throw new FormatException($"The model {nameof(UploadFileRequest)} does not support reading '{format}' format."); } using JsonDocument document = JsonDocument.ParseValue(ref reader); - return DeserializeCreateLivenessWithVerifySessionMultipartContent(document.RootElement, options); + return DeserializeUploadFileRequest(document.RootElement, options); } - internal static CreateLivenessWithVerifySessionMultipartContent DeserializeCreateLivenessWithVerifySessionMultipartContent(JsonElement element, ModelReaderWriterOptions options = null) + internal static UploadFileRequest DeserializeUploadFileRequest(JsonElement element, ModelReaderWriterOptions options = null) { options ??= ModelSerializationExtensions.WireOptions; @@ -83,20 +88,26 @@ internal static CreateLivenessWithVerifySessionMultipartContent DeserializeCreat { return null; } - CreateLivenessWithVerifySessionContent parameters = default; - Stream verifyImage = default; + Stream file = default; + FilePurpose purpose = default; + string filename = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) { - if (property.NameEquals("Parameters"u8)) + if (property.NameEquals("file"u8)) { - parameters = CreateLivenessWithVerifySessionContent.DeserializeCreateLivenessWithVerifySessionContent(property.Value, options); + file = BinaryData.FromString(property.Value.GetRawText()).ToStream(); continue; } - if (property.NameEquals("VerifyImage"u8)) + if (property.NameEquals("purpose"u8)) { - verifyImage = BinaryData.FromString(property.Value.GetRawText()).ToStream(); + purpose = new FilePurpose(property.Value.GetString()); + continue; + } + if (property.NameEquals("filename"u8)) + { + filename = property.Value.GetString(); continue; } if (options.Format != "W") @@ -105,7 +116,7 @@ internal static CreateLivenessWithVerifySessionMultipartContent DeserializeCreat } } serializedAdditionalRawData = rawDataDictionary; - return new CreateLivenessWithVerifySessionMultipartContent(parameters, verifyImage, serializedAdditionalRawData); + return new UploadFileRequest(file, purpose, filename, serializedAdditionalRawData); } private BinaryData SerializeMultipart(ModelReaderWriterOptions options) @@ -126,14 +137,18 @@ private BinaryData SerializeMultipart(ModelReaderWriterOptions options) internal virtual MultipartFormDataRequestContent ToMultipartRequestContent() { MultipartFormDataRequestContent content = new MultipartFormDataRequestContent(); - content.Add(ModelReaderWriter.Write(Parameters, ModelSerializationExtensions.WireOptions), "Parameters"); - content.Add(VerifyImage, "VerifyImage", "VerifyImage", "application/octet-stream"); + content.Add(Data, "file", "file", "application/octet-stream"); + content.Add(Purpose.ToString(), "purpose"); + if (Optional.IsDefined(Filename)) + { + content.Add(Filename, "filename"); + } return content; } - BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { @@ -142,34 +157,34 @@ BinaryData IPersistableModel.Wr case "MFD": return SerializeMultipart(options); default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support writing '{options.Format}' format."); + throw new FormatException($"The model {nameof(UploadFileRequest)} does not support writing '{options.Format}' format."); } } - CreateLivenessWithVerifySessionMultipartContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + UploadFileRequest IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) { - var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; switch (format) { case "J": { using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionMultipartContent(document.RootElement, options); + return DeserializeUploadFileRequest(document.RootElement, options); } default: - throw new FormatException($"The model {nameof(CreateLivenessWithVerifySessionMultipartContent)} does not support reading '{options.Format}' format."); + throw new FormatException($"The model {nameof(UploadFileRequest)} does not support reading '{options.Format}' format."); } } - string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "MFD"; /// Deserializes the model from a raw response. /// The response to deserialize the model from. - internal static CreateLivenessWithVerifySessionMultipartContent FromResponse(Response response) + internal static UploadFileRequest FromResponse(Response response) { using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); - return DeserializeCreateLivenessWithVerifySessionMultipartContent(document.RootElement); + return DeserializeUploadFileRequest(document.RootElement); } /// Convert into a . diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.cs new file mode 100644 index 000000000000..fd0a37af56b4 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadFileRequest.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.IO; + +namespace Azure.AI.OpenAI +{ + /// The UploadFileRequest. + public partial class UploadFileRequest + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// is null. + public UploadFileRequest(Stream data, FilePurpose purpose) + { + Argument.AssertNotNull(data, nameof(data)); + + Data = data; + Purpose = purpose; + } + + /// Initializes a new instance of . + /// The file data (not filename) to upload. + /// The intended purpose of the file. + /// A filename to associate with the uploaded data. + /// Keeps track of any properties unknown to the library. + internal UploadFileRequest(Stream data, FilePurpose purpose, string filename, IDictionary serializedAdditionalRawData) + { + Data = data; + Purpose = purpose; + Filename = filename; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal UploadFileRequest() + { + } + + /// The file data (not filename) to upload. + public Stream Data { get; } + /// The intended purpose of the file. + public FilePurpose Purpose { get; } + /// A filename to associate with the uploaded data. + public string Filename { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadObject.cs new file mode 100644 index 000000000000..649a57ce5a4c --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The Upload_object. + public readonly partial struct UploadObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadValue = "upload"; + + /// upload. + public static UploadObject Upload { get; } = new UploadObject(UploadValue); + /// Determines if two values are the same. + public static bool operator ==(UploadObject left, UploadObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadObject left, UploadObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadObject(string value) => new UploadObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadObject other && Equals(other); + /// + public bool Equals(UploadObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.Serialization.cs new file mode 100644 index 000000000000..025f031bef89 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.Serialization.cs @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class UploadPart : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UploadPart)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("id"u8); + writer.WriteStringValue(Id); + writer.WritePropertyName("created_at"u8); + writer.WriteNumberValue(CreatedAt, "U"); + writer.WritePropertyName("upload_id"u8); + writer.WriteStringValue(UploadId); + writer.WritePropertyName("object"u8); + writer.WriteStringValue(Object.ToString()); + if (Optional.IsDefined(AzureBlockId)) + { + writer.WritePropertyName("azure_block_id"u8); + writer.WriteStringValue(AzureBlockId); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + UploadPart IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UploadPart)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUploadPart(document.RootElement, options); + } + + internal static UploadPart DeserializeUploadPart(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string id = default; + DateTimeOffset createdAt = default; + string uploadId = default; + UploadPartObject @object = default; + string azureBlockId = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("id"u8)) + { + id = property.Value.GetString(); + continue; + } + if (property.NameEquals("created_at"u8)) + { + createdAt = DateTimeOffset.FromUnixTimeSeconds(property.Value.GetInt64()); + continue; + } + if (property.NameEquals("upload_id"u8)) + { + uploadId = property.Value.GetString(); + continue; + } + if (property.NameEquals("object"u8)) + { + @object = new UploadPartObject(property.Value.GetString()); + continue; + } + if (property.NameEquals("azure_block_id"u8)) + { + azureBlockId = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UploadPart( + id, + createdAt, + uploadId, + @object, + azureBlockId, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(UploadPart)} does not support writing '{options.Format}' format."); + } + } + + UploadPart IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUploadPart(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UploadPart)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UploadPart FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUploadPart(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.cs new file mode 100644 index 000000000000..2706e3f8f9cc --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPart.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// The upload Part represents a chunk of bytes we can add to an Upload object. + public partial class UploadPart + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The upload Part unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Part was created. + /// The ID of the Upload object that this Part was added to. + /// or is null. + internal UploadPart(string id, DateTimeOffset createdAt, string uploadId) + { + Argument.AssertNotNull(id, nameof(id)); + Argument.AssertNotNull(uploadId, nameof(uploadId)); + + Id = id; + CreatedAt = createdAt; + UploadId = uploadId; + } + + /// Initializes a new instance of . + /// The upload Part unique identifier, which can be referenced in API endpoints. + /// The Unix timestamp (in seconds) for when the Part was created. + /// The ID of the Upload object that this Part was added to. + /// The object type, which is always `upload.part`. + /// Azure only field. + /// Keeps track of any properties unknown to the library. + internal UploadPart(string id, DateTimeOffset createdAt, string uploadId, UploadPartObject @object, string azureBlockId, IDictionary serializedAdditionalRawData) + { + Id = id; + CreatedAt = createdAt; + UploadId = uploadId; + Object = @object; + AzureBlockId = azureBlockId; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal UploadPart() + { + } + + /// The upload Part unique identifier, which can be referenced in API endpoints. + public string Id { get; } + /// The Unix timestamp (in seconds) for when the Part was created. + public DateTimeOffset CreatedAt { get; } + /// The ID of the Upload object that this Part was added to. + public string UploadId { get; } + /// The object type, which is always `upload.part`. + public UploadPartObject Object { get; } = UploadPartObject.UploadPart; + + /// Azure only field. + public string AzureBlockId { get; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPartObject.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPartObject.cs new file mode 100644 index 000000000000..d161f3e609de --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPartObject.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The UploadPart_object. + public readonly partial struct UploadPartObject : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadPartObject(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string UploadPartValue = "upload.part"; + + /// upload.part. + public static UploadPartObject UploadPart { get; } = new UploadPartObject(UploadPartValue); + /// Determines if two values are the same. + public static bool operator ==(UploadPartObject left, UploadPartObject right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadPartObject left, UploadPartObject right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadPartObject(string value) => new UploadPartObject(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadPartObject other && Equals(other); + /// + public bool Equals(UploadPartObject other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPurpose.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPurpose.cs new file mode 100644 index 000000000000..69f7e4ccfb6b --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadPurpose.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The UploadPurpose. + public readonly partial struct UploadPurpose : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadPurpose(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string BatchValue = "batch"; + private const string BatchOutputValue = "batch_output"; + private const string FineTuneValue = "fine-tune"; + private const string FineTuneResultsValue = "fine-tune-results"; + private const string AssistantsValue = "assistants"; + private const string AssistantsOutputValue = "assistants_output"; + private const string VisionValue = "vision"; + + /// batch. + public static UploadPurpose Batch { get; } = new UploadPurpose(BatchValue); + /// batch_output. + public static UploadPurpose BatchOutput { get; } = new UploadPurpose(BatchOutputValue); + /// fine-tune. + public static UploadPurpose FineTune { get; } = new UploadPurpose(FineTuneValue); + /// fine-tune-results. + public static UploadPurpose FineTuneResults { get; } = new UploadPurpose(FineTuneResultsValue); + /// assistants. + public static UploadPurpose Assistants { get; } = new UploadPurpose(AssistantsValue); + /// assistants_output. + public static UploadPurpose AssistantsOutput { get; } = new UploadPurpose(AssistantsOutputValue); + /// vision. + public static UploadPurpose Vision { get; } = new UploadPurpose(VisionValue); + /// Determines if two values are the same. + public static bool operator ==(UploadPurpose left, UploadPurpose right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadPurpose left, UploadPurpose right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadPurpose(string value) => new UploadPurpose(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadPurpose other && Equals(other); + /// + public bool Equals(UploadPurpose other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadStatus.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadStatus.cs new file mode 100644 index 000000000000..bdb03110818d --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UploadStatus.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ComponentModel; + +namespace Azure.AI.OpenAI +{ + /// The UploadStatus. + public readonly partial struct UploadStatus : IEquatable + { + private readonly string _value; + + /// Initializes a new instance of . + /// is null. + public UploadStatus(string value) + { + _value = value ?? throw new ArgumentNullException(nameof(value)); + } + + private const string PendingValue = "pending"; + private const string CompletedValue = "completed"; + private const string CancelledValue = "cancelled"; + private const string ExpiredValue = "expired"; + + /// pending. + public static UploadStatus Pending { get; } = new UploadStatus(PendingValue); + /// completed. + public static UploadStatus Completed { get; } = new UploadStatus(CompletedValue); + /// cancelled. + public static UploadStatus Cancelled { get; } = new UploadStatus(CancelledValue); + /// expired. + public static UploadStatus Expired { get; } = new UploadStatus(ExpiredValue); + /// Determines if two values are the same. + public static bool operator ==(UploadStatus left, UploadStatus right) => left.Equals(right); + /// Determines if two values are not the same. + public static bool operator !=(UploadStatus left, UploadStatus right) => !left.Equals(right); + /// Converts a to a . + public static implicit operator UploadStatus(string value) => new UploadStatus(value); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override bool Equals(object obj) => obj is UploadStatus other && Equals(other); + /// + public bool Equals(UploadStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); + + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public override int GetHashCode() => _value != null ? StringComparer.InvariantCultureIgnoreCase.GetHashCode(_value) : 0; + /// + public override string ToString() => _value; + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.Serialization.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.Serialization.cs new file mode 100644 index 000000000000..c7db561a0c30 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.Serialization.cs @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.OpenAI +{ + public partial class UserSecurityContext : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UserSecurityContext)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(ApplicationName)) + { + writer.WritePropertyName("application_name"u8); + writer.WriteStringValue(ApplicationName); + } + if (Optional.IsDefined(EndUserId)) + { + writer.WritePropertyName("end_user_id"u8); + writer.WriteStringValue(EndUserId); + } + if (Optional.IsDefined(EndUserTenantId)) + { + writer.WritePropertyName("end_user_tenant_id"u8); + writer.WriteStringValue(EndUserTenantId); + } + if (Optional.IsDefined(SourceIp)) + { + writer.WritePropertyName("source_ip"u8); + writer.WriteStringValue(SourceIp); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + UserSecurityContext IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(UserSecurityContext)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeUserSecurityContext(document.RootElement, options); + } + + internal static UserSecurityContext DeserializeUserSecurityContext(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string applicationName = default; + string endUserId = default; + string endUserTenantId = default; + string sourceIp = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("application_name"u8)) + { + applicationName = property.Value.GetString(); + continue; + } + if (property.NameEquals("end_user_id"u8)) + { + endUserId = property.Value.GetString(); + continue; + } + if (property.NameEquals("end_user_tenant_id"u8)) + { + endUserTenantId = property.Value.GetString(); + continue; + } + if (property.NameEquals("source_ip"u8)) + { + sourceIp = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new UserSecurityContext(applicationName, endUserId, endUserTenantId, sourceIp, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(UserSecurityContext)} does not support writing '{options.Format}' format."); + } + } + + UserSecurityContext IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUserSecurityContext(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(UserSecurityContext)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static UserSecurityContext FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeUserSecurityContext(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.cs b/sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.cs new file mode 100644 index 000000000000..0687576719d9 --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/src/Generated/UserSecurityContext.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.OpenAI +{ + /// + /// User security context contains several parameters that describe the AI application itself, + /// and the end user that interacts with the AI application. These fields assist your security + /// operations teams to investigate and mitigate security incidents by providing a comprehensive + /// approach to protecting your AI applications. (Learn more at https://aka.ms/TP4AI/Documentation/EndUserContext) + /// about protecting AI applications using Microsoft Defender for Cloud. + /// + public partial class UserSecurityContext + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The name of the application. Sensitive personal information should not be included in this field. + /// This identifier is the Microsoft Entra ID (formerly Azure Active Directory) user object ID used to authenticate end-users within the generative AI application. Sensitive personal information should not be included in this field. + /// The Microsoft 365 tenant ID the end user belongs to. It's required when the generative AI application is multi tenant. + /// Captures the original client's IP address, accepting both IPv4 and IPv6 formats. + /// Keeps track of any properties unknown to the library. + internal UserSecurityContext(string applicationName, string endUserId, string endUserTenantId, string sourceIp, IDictionary serializedAdditionalRawData) + { + ApplicationName = applicationName; + EndUserId = endUserId; + EndUserTenantId = endUserTenantId; + SourceIp = sourceIp; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + /// Captures the original client's IP address, accepting both IPv4 and IPv6 formats. + public string SourceIp { get; set; } + } +} diff --git a/sdk/openai/Azure.AI.OpenAI/tsp-location.yaml b/sdk/openai/Azure.AI.OpenAI/tsp-location.yaml new file mode 100644 index 000000000000..c892b9bef60a --- /dev/null +++ b/sdk/openai/Azure.AI.OpenAI/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/cognitiveservices/OpenAI.Inference +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/playwrighttesting/Azure.Developer.MicrosoftPlaywrightTesting/tsp-location.yaml b/sdk/playwrighttesting/Azure.Developer.MicrosoftPlaywrightTesting/tsp-location.yaml new file mode 100644 index 000000000000..9de3f6772006 --- /dev/null +++ b/sdk/playwrighttesting/Azure.Developer.MicrosoftPlaywrightTesting/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/playwrighttesting/PlaywrightTesting.AuthManager +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Azure.Communication.ProgrammableConnectivity.sln b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Azure.Communication.ProgrammableConnectivity.sln new file mode 100644 index 000000000000..fc1ee5156b11 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Azure.Communication.ProgrammableConnectivity.sln @@ -0,0 +1,56 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29709.97 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Azure.Core.TestFramework", "..\..\core\Azure.Core.TestFramework\src\Azure.Core.TestFramework.csproj", "{ECC730C1-4AEA-420C-916A-66B19B79E4DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Communication.ProgrammableConnectivity", "src\Azure.Communication.ProgrammableConnectivity.csproj", "{28FF4005-4467-4E36-92E7-DEA27DEB1519}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Communication.ProgrammableConnectivity.Tests", "tests\Azure.Communication.ProgrammableConnectivity.Tests.csproj", "{1F1CD1D4-9932-4B73-99D8-C252A67D4B46}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B0C276D1-2930-4887-B29A-D1A33E7009A2}.Release|Any CPU.Build.0 = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8E9A77AC-792A-4432-8320-ACFD46730401}.Release|Any CPU.Build.0 = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ECC730C1-4AEA-420C-916A-66B19B79E4DC}.Release|Any CPU.Build.0 = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A4241C1F-A53D-474C-9E4E-075054407E74}.Release|Any CPU.Build.0 = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FA8BD3F1-8616-47B6-974C-7576CDF4717E}.Release|Any CPU.Build.0 = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {85677AD3-C214-42FA-AE6E-49B956CAC8DC}.Release|Any CPU.Build.0 = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Debug|Any CPU.Build.0 = Debug|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.ActiveCfg = Release|Any CPU + {28FF4005-4467-4E36-92E7-DEA27DEB1519}.Release|Any CPU.Build.0 = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1F1CD1D4-9932-4B73-99D8-C252A67D4B46}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A97F4B90-2591-4689-B1F8-5F21FE6D6CAE} + EndGlobalSection +EndGlobal diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/CHANGELOG.md b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/CHANGELOG.md new file mode 100644 index 000000000000..8b33f0fedccc --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/CHANGELOG.md @@ -0,0 +1,11 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes \ No newline at end of file diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Directory.Build.props b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Directory.Build.props new file mode 100644 index 000000000000..63bd836ad44b --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/Directory.Build.props @@ -0,0 +1,6 @@ + + + + diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/README.md b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/README.md new file mode 100644 index 000000000000..526c34e3fe7d --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/README.md @@ -0,0 +1,107 @@ +# Azure.Communication.ProgrammableConnectivity client library for .NET + +Azure.Communication.ProgrammableConnectivity is a managed service that helps developers get secret simply and securely. + +Use the client library for to: + +* [Get secret](https://docs.microsoft.com/azure) + +[Source code][source_root] | [Package (NuGet)][package] | [API reference documentation][reference_docs] | [Product documentation][azconfig_docs] | [Samples][source_samples] + + [Source code](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src) | [Package (NuGet)](https://www.nuget.org/packages) | [API reference documentation](https://azure.github.io/azure-sdk-for-net) | [Product documentation](https://docs.microsoft.com/azure) + +## Getting started + +This section should include everything a developer needs to do to install and create their first client connection *very quickly*. + +### Install the package + +First, provide instruction for obtaining and installing the package or library. This section might include only a single line of code, like `dotnet add package package-name`, but should enable a developer to successfully install the package from NuGet, npm, or even cloning a GitHub repository. + +Install the client library for .NET with [NuGet](https://www.nuget.org/ ): + +```dotnetcli +dotnet add package Azure.Communication.ProgrammableConnectivity --prerelease +``` + +### Prerequisites + +Include a section after the install command that details any requirements that must be satisfied before a developer can [authenticate](#authenticate-the-client) and test all of the snippets in the [Examples](#examples) section. For example, for Cosmos DB: + +> You must have an [Azure subscription](https://azure.microsoft.com/free/dotnet/) and [Cosmos DB account](https://docs.microsoft.com/azure/cosmos-db/account-overview) (SQL API). In order to take advantage of the C# 8.0 syntax, it is recommended that you compile using the [.NET Core SDK](https://dotnet.microsoft.com/download) 3.0 or higher with a [language version](https://docs.microsoft.com/dotnet/csharp/language-reference/configure-language-version#override-a-default) of `latest`. It is also possible to compile with the .NET Core SDK 2.1.x using a language version of `preview`. + +### Authenticate the client + +If your library requires authentication for use, such as for Azure services, include instructions and example code needed for initializing and authenticating. + +For example, include details on obtaining an account key and endpoint URI, setting environment variables for each, and initializing the client object. + +### Service API versions + +The client library targets the latest service API version by default. A client instance accepts an optional service API version parameter from its options to specify which API version service to communicate. + +#### Select a service API version + +You have the flexibility to explicitly select a supported service API version when instantiating a client by configuring its associated options. This ensures that the client can communicate with services using the specified API version. + +For example, + +```C# Snippet:CreateClientForSpecificApiVersion +Uri endpoint = new Uri(""); +DefaultAzureCredential credential = new DefaultAzureCredential(); +ClientOptions options = new ClientOptions(ClientOptions.ServiceVersion.) +var client = new Client(endpoint, credential, options); +``` + +When selecting an API version, it's important to verify that there are no breaking changes compared to the latest API version. If there are significant differences, API calls may fail due to incompatibility. + +Always ensure that the chosen API version is fully supported and operational for your specific use case and that it aligns with the service's versioning policy. + +## Key concepts + +The *Key concepts* section should describe the functionality of the main classes. Point out the most important and useful classes in the package (with links to their reference pages) and explain how those classes work together. Feel free to use bulleted lists, tables, code blocks, or even diagrams for clarity. + +Include the *Thread safety* and *Additional concepts* sections below at the end of your *Key concepts* section. You may remove or add links depending on what your library makes use of: + +### Thread safety + +We guarantee that all client instance methods are thread-safe and independent of each other ([guideline](https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-service-methods-thread-safety)). This ensures that the recommendation of reusing client instances is always safe, even across threads. + +### Additional concepts + +[Client options](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#configuring-service-clients-using-clientoptions) | +[Accessing the response](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#accessing-http-response-details-using-responset) | +[Long-running operations](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#consuming-long-running-operations-using-operationt) | +[Handling failures](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#reporting-errors-requestfailedexception) | +[Diagnostics](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Diagnostics.md) | +[Mocking](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/README.md#mocking) | +[Client lifetime](https://devblogs.microsoft.com/azure-sdk/lifetime-management-and-thread-safety-guarantees-of-azure-sdk-net-clients/) + + +## Examples + +You can familiarize yourself with different APIs using [Samples](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/samples). + +## Troubleshooting + +Describe common errors and exceptions, how to "unpack" them if necessary, and include guidance for graceful handling and recovery. + +Provide information to help developers avoid throttling or other service-enforced errors they might encounter. For example, provide guidance and examples for using retry or connection policies in the API. + +If the package or a related package supports it, include tips for logging or enabling instrumentation to help them debug their code. + +## Next steps + +* Provide a link to additional code examples, ideally to those sitting alongside the README in the package's `/samples` directory. +* If appropriate, point users to other packages that might be useful. +* If you think there's a good chance that developers might stumble across your package in error (because they're searching for specific functionality and mistakenly think the package provides that functionality), point them to the packages they might be looking for. + +## Contributing + +This is a template, but your SDK readme should include details on how to contribute code to the repo/package. + + +[style-guide-msft]: https://docs.microsoft.com/style-guide/capitalization +[style-guide-cloud]: https://aka.ms/azsdk/cloud-style-guide + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/README.png) \ No newline at end of file diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.net8.0.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.net8.0.cs new file mode 100644 index 000000000000..85a549cce78a --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.net8.0.cs @@ -0,0 +1,255 @@ +namespace Azure.Communication.ProgrammableConnectivity +{ + public static partial class CommunicationProgrammableConnectivityModelFactory + { + public static Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationResult DeviceLocationVerificationResult(bool verificationResult = false) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.NetworkRetrievalResult NetworkRetrievalResult(string networkCode = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.NumberVerificationResult NumberVerificationResult(bool verificationResult = false) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent NumberVerificationWithoutCodeContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier = null, string phoneNumber = null, string hashedPhoneNumber = null, System.Uri redirectUri = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent SimSwapRetrievalContent(string phoneNumber = null, Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalResult SimSwapRetrievalResult(System.DateTimeOffset? date = default(System.DateTimeOffset?)) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent SimSwapVerificationContent(string phoneNumber = null, int? maxAgeHours = default(int?), Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapVerificationResult SimSwapVerificationResult(bool verificationResult = false) { throw null; } + } + public partial class DeviceLocation + { + protected DeviceLocation() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> VerifyAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class DeviceLocationVerificationContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public DeviceLocationVerificationContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier, double latitude, double longitude, int accuracy, Azure.Communication.ProgrammableConnectivity.LocationDevice device) { } + public int Accuracy { get { throw null; } } + public Azure.Communication.ProgrammableConnectivity.LocationDevice Device { get { throw null; } } + public double Latitude { get { throw null; } } + public double Longitude { get { throw null; } } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class DeviceLocationVerificationResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal DeviceLocationVerificationResult() { } + public bool VerificationResult { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class DeviceNetwork + { + protected DeviceNetwork() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NetworkIdentifier body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> RetrieveAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NetworkIdentifier body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task RetrieveAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class Ipv4Address : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public Ipv4Address(string ipv4, int port) { } + public string Ipv4 { get { throw null; } } + public int Port { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv4Address System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv4Address System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class Ipv6Address : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public Ipv6Address(string ipv6, int port) { } + public string Ipv6 { get { throw null; } } + public int Port { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv6Address System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv6Address System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class LocationDevice : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public LocationDevice() { } + public Azure.Communication.ProgrammableConnectivity.Ipv4Address Ipv4Address { get { throw null; } set { } } + public Azure.Communication.ProgrammableConnectivity.Ipv6Address Ipv6Address { get { throw null; } set { } } + public string NetworkAccessIdentifier { get { throw null; } set { } } + public string PhoneNumber { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.LocationDevice System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.LocationDevice System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NetworkIdentifier : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public NetworkIdentifier(string identifierType, string identifier) { } + public string Identifier { get { throw null; } } + public string IdentifierType { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkIdentifier System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkIdentifier System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NetworkRetrievalResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal NetworkRetrievalResult() { } + public string NetworkCode { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkRetrievalResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkRetrievalResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NumberVerification + { + protected NumberVerification() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response VerifyWithCode(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response VerifyWithCode(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> VerifyWithCodeAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyWithCodeAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response VerifyWithoutCode(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response VerifyWithoutCode(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task VerifyWithoutCodeAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyWithoutCodeAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class NumberVerificationResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal NumberVerificationResult() { } + public bool VerificationResult { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NumberVerificationWithCodeContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public NumberVerificationWithCodeContent(string apcCode) { } + public string ApcCode { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NumberVerificationWithoutCodeContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public NumberVerificationWithoutCodeContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier, System.Uri redirectUri) { } + public string HashedPhoneNumber { get { throw null; } set { } } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + public string PhoneNumber { get { throw null; } set { } } + public System.Uri RedirectUri { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class ProgrammableConnectivityClient + { + protected ProgrammableConnectivityClient() { } + public ProgrammableConnectivityClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } + public ProgrammableConnectivityClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Communication.ProgrammableConnectivity.ProgrammableConnectivityClientOptions options) { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Communication.ProgrammableConnectivity.DeviceLocation GetDeviceLocationClient(string apiVersion = "2024-02-09-preview") { throw null; } + public virtual Azure.Communication.ProgrammableConnectivity.DeviceNetwork GetDeviceNetworkClient(string apiVersion = "2024-02-09-preview") { throw null; } + public virtual Azure.Communication.ProgrammableConnectivity.NumberVerification GetNumberVerificationClient(string apiVersion = "2024-02-09-preview") { throw null; } + public virtual Azure.Communication.ProgrammableConnectivity.SimSwap GetSimSwapClient(string apiVersion = "2024-02-09-preview") { throw null; } + } + public partial class ProgrammableConnectivityClientOptions : Azure.Core.ClientOptions + { + public ProgrammableConnectivityClientOptions(Azure.Communication.ProgrammableConnectivity.ProgrammableConnectivityClientOptions.ServiceVersion version = Azure.Communication.ProgrammableConnectivity.ProgrammableConnectivityClientOptions.ServiceVersion.V2024_02_09_Preview) { } + public enum ServiceVersion + { + V2024_02_09_Preview = 1, + } + } + public partial class SimSwap + { + protected SimSwap() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> RetrieveAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task RetrieveAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> VerifyAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class SimSwapRetrievalContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public SimSwapRetrievalContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier) { } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + public string PhoneNumber { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class SimSwapRetrievalResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal SimSwapRetrievalResult() { } + public System.DateTimeOffset? Date { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class SimSwapVerificationContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public SimSwapVerificationContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier) { } + public int? MaxAgeHours { get { throw null; } set { } } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + public string PhoneNumber { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class SimSwapVerificationResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal SimSwapVerificationResult() { } + public bool VerificationResult { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } +} +namespace Microsoft.Extensions.Azure +{ + public static partial class CommunicationProgrammableConnectivityClientBuilderExtensions + { + public static Azure.Core.Extensions.IAzureClientBuilder AddProgrammableConnectivityClient(this TBuilder builder, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddProgrammableConnectivityClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.netstandard2.0.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.netstandard2.0.cs new file mode 100644 index 000000000000..85a549cce78a --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/api/Azure.Communication.ProgrammableConnectivity.netstandard2.0.cs @@ -0,0 +1,255 @@ +namespace Azure.Communication.ProgrammableConnectivity +{ + public static partial class CommunicationProgrammableConnectivityModelFactory + { + public static Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationResult DeviceLocationVerificationResult(bool verificationResult = false) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.NetworkRetrievalResult NetworkRetrievalResult(string networkCode = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.NumberVerificationResult NumberVerificationResult(bool verificationResult = false) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent NumberVerificationWithoutCodeContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier = null, string phoneNumber = null, string hashedPhoneNumber = null, System.Uri redirectUri = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent SimSwapRetrievalContent(string phoneNumber = null, Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalResult SimSwapRetrievalResult(System.DateTimeOffset? date = default(System.DateTimeOffset?)) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent SimSwapVerificationContent(string phoneNumber = null, int? maxAgeHours = default(int?), Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier = null) { throw null; } + public static Azure.Communication.ProgrammableConnectivity.SimSwapVerificationResult SimSwapVerificationResult(bool verificationResult = false) { throw null; } + } + public partial class DeviceLocation + { + protected DeviceLocation() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> VerifyAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class DeviceLocationVerificationContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public DeviceLocationVerificationContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier, double latitude, double longitude, int accuracy, Azure.Communication.ProgrammableConnectivity.LocationDevice device) { } + public int Accuracy { get { throw null; } } + public Azure.Communication.ProgrammableConnectivity.LocationDevice Device { get { throw null; } } + public double Latitude { get { throw null; } } + public double Longitude { get { throw null; } } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class DeviceLocationVerificationResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal DeviceLocationVerificationResult() { } + public bool VerificationResult { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.DeviceLocationVerificationResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class DeviceNetwork + { + protected DeviceNetwork() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NetworkIdentifier body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> RetrieveAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NetworkIdentifier body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task RetrieveAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class Ipv4Address : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public Ipv4Address(string ipv4, int port) { } + public string Ipv4 { get { throw null; } } + public int Port { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv4Address System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv4Address System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class Ipv6Address : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public Ipv6Address(string ipv6, int port) { } + public string Ipv6 { get { throw null; } } + public int Port { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv6Address System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.Ipv6Address System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class LocationDevice : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public LocationDevice() { } + public Azure.Communication.ProgrammableConnectivity.Ipv4Address Ipv4Address { get { throw null; } set { } } + public Azure.Communication.ProgrammableConnectivity.Ipv6Address Ipv6Address { get { throw null; } set { } } + public string NetworkAccessIdentifier { get { throw null; } set { } } + public string PhoneNumber { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.LocationDevice System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.LocationDevice System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NetworkIdentifier : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public NetworkIdentifier(string identifierType, string identifier) { } + public string Identifier { get { throw null; } } + public string IdentifierType { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkIdentifier System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkIdentifier System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NetworkRetrievalResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal NetworkRetrievalResult() { } + public string NetworkCode { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkRetrievalResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NetworkRetrievalResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NumberVerification + { + protected NumberVerification() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response VerifyWithCode(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response VerifyWithCode(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> VerifyWithCodeAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyWithCodeAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response VerifyWithoutCode(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response VerifyWithoutCode(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task VerifyWithoutCodeAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyWithoutCodeAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class NumberVerificationResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal NumberVerificationResult() { } + public bool VerificationResult { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NumberVerificationWithCodeContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public NumberVerificationWithCodeContent(string apcCode) { } + public string ApcCode { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithCodeContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class NumberVerificationWithoutCodeContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public NumberVerificationWithoutCodeContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier, System.Uri redirectUri) { } + public string HashedPhoneNumber { get { throw null; } set { } } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + public string PhoneNumber { get { throw null; } set { } } + public System.Uri RedirectUri { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.NumberVerificationWithoutCodeContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class ProgrammableConnectivityClient + { + protected ProgrammableConnectivityClient() { } + public ProgrammableConnectivityClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } + public ProgrammableConnectivityClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Communication.ProgrammableConnectivity.ProgrammableConnectivityClientOptions options) { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Communication.ProgrammableConnectivity.DeviceLocation GetDeviceLocationClient(string apiVersion = "2024-02-09-preview") { throw null; } + public virtual Azure.Communication.ProgrammableConnectivity.DeviceNetwork GetDeviceNetworkClient(string apiVersion = "2024-02-09-preview") { throw null; } + public virtual Azure.Communication.ProgrammableConnectivity.NumberVerification GetNumberVerificationClient(string apiVersion = "2024-02-09-preview") { throw null; } + public virtual Azure.Communication.ProgrammableConnectivity.SimSwap GetSimSwapClient(string apiVersion = "2024-02-09-preview") { throw null; } + } + public partial class ProgrammableConnectivityClientOptions : Azure.Core.ClientOptions + { + public ProgrammableConnectivityClientOptions(Azure.Communication.ProgrammableConnectivity.ProgrammableConnectivityClientOptions.ServiceVersion version = Azure.Communication.ProgrammableConnectivity.ProgrammableConnectivityClientOptions.ServiceVersion.V2024_02_09_Preview) { } + public enum ServiceVersion + { + V2024_02_09_Preview = 1, + } + } + public partial class SimSwap + { + protected SimSwap() { } + public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Retrieve(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> RetrieveAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task RetrieveAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Verify(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> VerifyAsync(string apcGatewayId, Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task VerifyAsync(string apcGatewayId, Azure.Core.RequestContent content, Azure.RequestContext context = null) { throw null; } + } + public partial class SimSwapRetrievalContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public SimSwapRetrievalContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier) { } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + public string PhoneNumber { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class SimSwapRetrievalResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal SimSwapRetrievalResult() { } + public System.DateTimeOffset? Date { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapRetrievalResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class SimSwapVerificationContent : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public SimSwapVerificationContent(Azure.Communication.ProgrammableConnectivity.NetworkIdentifier networkIdentifier) { } + public int? MaxAgeHours { get { throw null; } set { } } + public Azure.Communication.ProgrammableConnectivity.NetworkIdentifier NetworkIdentifier { get { throw null; } } + public string PhoneNumber { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationContent System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } + public partial class SimSwapVerificationResult : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + internal SimSwapVerificationResult() { } + public bool VerificationResult { get { throw null; } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationResult System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.Communication.ProgrammableConnectivity.SimSwapVerificationResult System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } +} +namespace Microsoft.Extensions.Azure +{ + public static partial class CommunicationProgrammableConnectivityClientBuilderExtensions + { + public static Azure.Core.Extensions.IAzureClientBuilder AddProgrammableConnectivityClient(this TBuilder builder, System.Uri endpoint) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } + public static Azure.Core.Extensions.IAzureClientBuilder AddProgrammableConnectivityClient(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration { throw null; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Azure.Communication.ProgrammableConnectivity.csproj b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Azure.Communication.ProgrammableConnectivity.csproj new file mode 100644 index 000000000000..a3206b8c2f96 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Azure.Communication.ProgrammableConnectivity.csproj @@ -0,0 +1,19 @@ + + + This is the Azure.Communication.ProgrammableConnectivity client library for developing .NET applications with rich experience. + Azure SDK Code Generation Azure.Communication.ProgrammableConnectivity for Azure Data Plane + 1.0.0-beta.1 + Azure.Communication.ProgrammableConnectivity + $(RequiredTargetFrameworks) + true + + + + + + + + + + + diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityClientBuilderExtensions.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityClientBuilderExtensions.cs new file mode 100644 index 000000000000..e5e56416b03c --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityClientBuilderExtensions.cs @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Communication.ProgrammableConnectivity; +using Azure.Core.Extensions; + +namespace Microsoft.Extensions.Azure +{ + /// Extension methods to add to client builder. + public static partial class CommunicationProgrammableConnectivityClientBuilderExtensions + { + /// Registers a instance. + /// The builder to register with. + /// An Azure Programmable Connectivity Endpoint providing access to Network APIs, for example https://{region}.apcgatewayapi.azure.com. + public static IAzureClientBuilder AddProgrammableConnectivityClient(this TBuilder builder, Uri endpoint) + where TBuilder : IAzureClientFactoryBuilderWithCredential + { + return builder.RegisterClientFactory((options, cred) => new ProgrammableConnectivityClient(endpoint, cred, options)); + } + + /// Registers a instance. + /// The builder to register with. + /// The configuration values. + public static IAzureClientBuilder AddProgrammableConnectivityClient(this TBuilder builder, TConfiguration configuration) + where TBuilder : IAzureClientFactoryBuilderWithConfiguration + { + return builder.RegisterClientFactory(configuration); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityModelFactory.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityModelFactory.cs new file mode 100644 index 000000000000..10a3a049d2e7 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/CommunicationProgrammableConnectivityModelFactory.cs @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Model factory for models. + public static partial class CommunicationProgrammableConnectivityModelFactory + { + /// Initializes a new instance of . + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + /// Network to query for this device. + /// A new instance for mocking. + public static SimSwapRetrievalContent SimSwapRetrievalContent(string phoneNumber = null, NetworkIdentifier networkIdentifier = null) + { + return new SimSwapRetrievalContent(phoneNumber, networkIdentifier, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Datetime of most recent swap for SIM. + /// A new instance for mocking. + public static SimSwapRetrievalResult SimSwapRetrievalResult(DateTimeOffset? date = null) + { + return new SimSwapRetrievalResult(date, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + /// Maximum lookback for SimSwap verification. + /// Identifier for the network to query for this device. + /// A new instance for mocking. + public static SimSwapVerificationContent SimSwapVerificationContent(string phoneNumber = null, int? maxAgeHours = null, NetworkIdentifier networkIdentifier = null) + { + return new SimSwapVerificationContent(phoneNumber, maxAgeHours, networkIdentifier, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// True if the SIM has swapped in the specified period, False otherwise. + /// A new instance for mocking. + public static SimSwapVerificationResult SimSwapVerificationResult(bool verificationResult = default) + { + return new SimSwapVerificationResult(verificationResult, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// Identifier for the network to query for this device. + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + /// Hashed phone number. SHA-256 (in hexadecimal representation) of the mobile phone number in **E.164 format (starting with country code)**. Optionally prefixed with '+'. + /// Redirect URI to backend application. + /// A new instance for mocking. + public static NumberVerificationWithoutCodeContent NumberVerificationWithoutCodeContent(NetworkIdentifier networkIdentifier = null, string phoneNumber = null, string hashedPhoneNumber = null, Uri redirectUri = null) + { + return new NumberVerificationWithoutCodeContent(networkIdentifier, phoneNumber, hashedPhoneNumber, redirectUri, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// True if number if the phone number matches the device, False otherwise. + /// A new instance for mocking. + public static NumberVerificationResult NumberVerificationResult(bool verificationResult = default) + { + return new NumberVerificationResult(verificationResult, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// The identifier for the network. This can be used as the networkIdentifier for the service APIs. + /// A new instance for mocking. + public static NetworkRetrievalResult NetworkRetrievalResult(string networkCode = null) + { + return new NetworkRetrievalResult(networkCode, serializedAdditionalRawData: null); + } + + /// Initializes a new instance of . + /// True if the location is in the specified area, False otherwise. + /// A new instance for mocking. + public static DeviceLocationVerificationResult DeviceLocationVerificationResult(bool verificationResult = default) + { + return new DeviceLocationVerificationResult(verificationResult, serializedAdditionalRawData: null); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocation.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocation.cs new file mode 100644 index 000000000000..927683a9c7ad --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocation.cs @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Communication.ProgrammableConnectivity +{ + // Data plane generated sub-client. + /// The DeviceLocation sub-client. + public partial class DeviceLocation + { + private static readonly string[] AuthorizationScopes = new string[] { "https://management.azure.com//.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of DeviceLocation for mocking. + protected DeviceLocation() + { + } + + /// Initializes a new instance of DeviceLocation. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// An Azure Programmable Connectivity Endpoint providing access to Network APIs, for example https://{region}.apcgatewayapi.azure.com. + /// The API version to use for this operation. + internal DeviceLocation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Verifies whether a device is within a specified location area, defined as an accuracy (radius) around a point, specified by longitude and latitude. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task> VerifyAsync(string apcGatewayId, DeviceLocationVerificationContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await VerifyAsync(apcGatewayId, content, context).ConfigureAwait(false); + return Response.FromValue(DeviceLocationVerificationResult.FromResponse(response), response); + } + + /// Verifies whether a device is within a specified location area, defined as an accuracy (radius) around a point, specified by longitude and latitude. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual Response Verify(string apcGatewayId, DeviceLocationVerificationContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Verify(apcGatewayId, content, context); + return Response.FromValue(DeviceLocationVerificationResult.FromResponse(response), response); + } + + /// + /// [Protocol Method] Verifies whether a device is within a specified location area, defined as an accuracy (radius) around a point, specified by longitude and latitude. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task VerifyAsync(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("DeviceLocation.Verify"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyRequest(apcGatewayId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Verifies whether a device is within a specified location area, defined as an accuracy (radius) around a point, specified by longitude and latitude. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Verify(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("DeviceLocation.Verify"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyRequest(apcGatewayId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateVerifyRequest(string apcGatewayId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/device-location/location:verify", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("apc-gateway-id", apcGatewayId); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.Serialization.cs new file mode 100644 index 000000000000..341f6679f7d5 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.Serialization.cs @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class DeviceLocationVerificationContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DeviceLocationVerificationContent)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("networkIdentifier"u8); + writer.WriteObjectValue(NetworkIdentifier, options); + writer.WritePropertyName("latitude"u8); + writer.WriteNumberValue(Latitude); + writer.WritePropertyName("longitude"u8); + writer.WriteNumberValue(Longitude); + writer.WritePropertyName("accuracy"u8); + writer.WriteNumberValue(Accuracy); + writer.WritePropertyName("device"u8); + writer.WriteObjectValue(Device, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DeviceLocationVerificationContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DeviceLocationVerificationContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDeviceLocationVerificationContent(document.RootElement, options); + } + + internal static DeviceLocationVerificationContent DeserializeDeviceLocationVerificationContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + NetworkIdentifier networkIdentifier = default; + double latitude = default; + double longitude = default; + int accuracy = default; + LocationDevice device = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("networkIdentifier"u8)) + { + networkIdentifier = NetworkIdentifier.DeserializeNetworkIdentifier(property.Value, options); + continue; + } + if (property.NameEquals("latitude"u8)) + { + latitude = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("longitude"u8)) + { + longitude = property.Value.GetDouble(); + continue; + } + if (property.NameEquals("accuracy"u8)) + { + accuracy = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("device"u8)) + { + device = LocationDevice.DeserializeLocationDevice(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DeviceLocationVerificationContent( + networkIdentifier, + latitude, + longitude, + accuracy, + device, + serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DeviceLocationVerificationContent)} does not support writing '{options.Format}' format."); + } + } + + DeviceLocationVerificationContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDeviceLocationVerificationContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DeviceLocationVerificationContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DeviceLocationVerificationContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDeviceLocationVerificationContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.cs new file mode 100644 index 000000000000..64761dc7ca20 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationContent.cs @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Request to verify Location. + public partial class DeviceLocationVerificationContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Network to query for this device, or device information to enable network routing. + /// Latitude of location to be verified. + /// Longitude of location to be verified. + /// Accuracy expected for location verification in kilometers. + /// The device to find the location for. Exactly one of Network Access Code, Phone Number, IPv4 address, or IPv6 address. + /// or is null. + public DeviceLocationVerificationContent(NetworkIdentifier networkIdentifier, double latitude, double longitude, int accuracy, LocationDevice device) + { + Argument.AssertNotNull(networkIdentifier, nameof(networkIdentifier)); + Argument.AssertNotNull(device, nameof(device)); + + NetworkIdentifier = networkIdentifier; + Latitude = latitude; + Longitude = longitude; + Accuracy = accuracy; + Device = device; + } + + /// Initializes a new instance of . + /// Network to query for this device, or device information to enable network routing. + /// Latitude of location to be verified. + /// Longitude of location to be verified. + /// Accuracy expected for location verification in kilometers. + /// The device to find the location for. Exactly one of Network Access Code, Phone Number, IPv4 address, or IPv6 address. + /// Keeps track of any properties unknown to the library. + internal DeviceLocationVerificationContent(NetworkIdentifier networkIdentifier, double latitude, double longitude, int accuracy, LocationDevice device, IDictionary serializedAdditionalRawData) + { + NetworkIdentifier = networkIdentifier; + Latitude = latitude; + Longitude = longitude; + Accuracy = accuracy; + Device = device; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DeviceLocationVerificationContent() + { + } + + /// Network to query for this device, or device information to enable network routing. + public NetworkIdentifier NetworkIdentifier { get; } + /// Latitude of location to be verified. + public double Latitude { get; } + /// Longitude of location to be verified. + public double Longitude { get; } + /// Accuracy expected for location verification in kilometers. + public int Accuracy { get; } + /// The device to find the location for. Exactly one of Network Access Code, Phone Number, IPv4 address, or IPv6 address. + public LocationDevice Device { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.Serialization.cs new file mode 100644 index 000000000000..32cade07d824 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class DeviceLocationVerificationResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DeviceLocationVerificationResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("verificationResult"u8); + writer.WriteBooleanValue(VerificationResult); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + DeviceLocationVerificationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(DeviceLocationVerificationResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeDeviceLocationVerificationResult(document.RootElement, options); + } + + internal static DeviceLocationVerificationResult DeserializeDeviceLocationVerificationResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool verificationResult = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("verificationResult"u8)) + { + verificationResult = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new DeviceLocationVerificationResult(verificationResult, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(DeviceLocationVerificationResult)} does not support writing '{options.Format}' format."); + } + } + + DeviceLocationVerificationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDeviceLocationVerificationResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(DeviceLocationVerificationResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static DeviceLocationVerificationResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeDeviceLocationVerificationResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.cs new file mode 100644 index 000000000000..dff7039b7fff --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceLocationVerificationResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Response verifying location. + public partial class DeviceLocationVerificationResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// True if the location is in the specified area, False otherwise. + internal DeviceLocationVerificationResult(bool verificationResult) + { + VerificationResult = verificationResult; + } + + /// Initializes a new instance of . + /// True if the location is in the specified area, False otherwise. + /// Keeps track of any properties unknown to the library. + internal DeviceLocationVerificationResult(bool verificationResult, IDictionary serializedAdditionalRawData) + { + VerificationResult = verificationResult; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal DeviceLocationVerificationResult() + { + } + + /// True if the location is in the specified area, False otherwise. + public bool VerificationResult { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceNetwork.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceNetwork.cs new file mode 100644 index 000000000000..d2c1e51dee07 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/DeviceNetwork.cs @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Communication.ProgrammableConnectivity +{ + // Data plane generated sub-client. + /// The DeviceNetwork sub-client. + public partial class DeviceNetwork + { + private static readonly string[] AuthorizationScopes = new string[] { "https://management.azure.com//.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of DeviceNetwork for mocking. + protected DeviceNetwork() + { + } + + /// Initializes a new instance of DeviceNetwork. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// An Azure Programmable Connectivity Endpoint providing access to Network APIs, for example https://{region}.apcgatewayapi.azure.com. + /// The API version to use for this operation. + internal DeviceNetwork(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Retrieves the network a given device is on. Returns network in a networkCode format that can be used for other APIs. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task> RetrieveAsync(string apcGatewayId, NetworkIdentifier body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await RetrieveAsync(apcGatewayId, content, context).ConfigureAwait(false); + return Response.FromValue(NetworkRetrievalResult.FromResponse(response), response); + } + + /// Retrieves the network a given device is on. Returns network in a networkCode format that can be used for other APIs. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual Response Retrieve(string apcGatewayId, NetworkIdentifier body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Retrieve(apcGatewayId, content, context); + return Response.FromValue(NetworkRetrievalResult.FromResponse(response), response); + } + + /// + /// [Protocol Method] Retrieves the network a given device is on. Returns network in a networkCode format that can be used for other APIs. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task RetrieveAsync(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("DeviceNetwork.Retrieve"); + scope.Start(); + try + { + using HttpMessage message = CreateRetrieveRequest(apcGatewayId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Retrieves the network a given device is on. Returns network in a networkCode format that can be used for other APIs. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Retrieve(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("DeviceNetwork.Retrieve"); + scope.Start(); + try + { + using HttpMessage message = CreateRetrieveRequest(apcGatewayId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateRetrieveRequest(string apcGatewayId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/device-network/network:retrieve", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("apc-gateway-id", apcGatewayId); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceLocation.xml b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceLocation.xml new file mode 100644 index 000000000000..7f0e9857ff68 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceLocation.xml @@ -0,0 +1,121 @@ + + + + + +This sample shows how to call VerifyAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + +DeviceLocationVerificationContent body = new DeviceLocationVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12"), 70, -161, 91, new LocationDevice +{ + NetworkAccessIdentifier = "122345@domain.com", + PhoneNumber = "+447000000000", + Ipv4Address = new Ipv4Address("12.12.12.12", 2442), + Ipv6Address = new Ipv6Address("3001:0da8:75a3:0000:0000:8a2e:0370:7334", 1643), +}); +Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call Verify. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + +DeviceLocationVerificationContent body = new DeviceLocationVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12"), 70, -161, 91, new LocationDevice +{ + NetworkAccessIdentifier = "122345@domain.com", + PhoneNumber = "+447000000000", + Ipv4Address = new Ipv4Address("12.12.12.12", 2442), + Ipv6Address = new Ipv6Address("3001:0da8:75a3:0000:0000:8a2e:0370:7334", 1643), +}); +Response response = client.Verify("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call VerifyAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + latitude = 70, + longitude = -161, + accuracy = 91, + device = new + { + networkAccessIdentifier = "122345@domain.com", + phoneNumber = "+447000000000", + ipv4Address = new + { + ipv4 = "12.12.12.12", + port = 2442, + }, + ipv6Address = new + { + ipv6 = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", + port = 1643, + }, + }, +}); +Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("verificationResult").ToString()); +]]> + + + +This sample shows how to call Verify and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + latitude = 70, + longitude = -161, + accuracy = 91, + device = new + { + networkAccessIdentifier = "122345@domain.com", + phoneNumber = "+447000000000", + ipv4Address = new + { + ipv4 = "12.12.12.12", + port = 2442, + }, + ipv6Address = new + { + ipv6 = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", + port = 1643, + }, + }, +}); +Response response = client.Verify("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("verificationResult").ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceNetwork.xml b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceNetwork.xml new file mode 100644 index 000000000000..8d5a6738ca72 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/DeviceNetwork.xml @@ -0,0 +1,67 @@ + + + + + +This sample shows how to call RetrieveAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + +NetworkIdentifier body = new NetworkIdentifier("ipv6", "3001:0da8:75a3:0000:0000:8a2e:0370:7334"); +Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call Retrieve. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + +NetworkIdentifier body = new NetworkIdentifier("ipv6", "3001:0da8:75a3:0000:0000:8a2e:0370:7334"); +Response response = client.Retrieve("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call RetrieveAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + identifierType = "ipv6", + identifier = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", +}); +Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("networkCode").ToString()); +]]> + + + +This sample shows how to call Retrieve and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + identifierType = "ipv6", + identifier = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", +}); +Response response = client.Retrieve("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("networkCode").ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/NumberVerification.xml b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/NumberVerification.xml new file mode 100644 index 000000000000..b3d44f324795 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/NumberVerification.xml @@ -0,0 +1,145 @@ + + + + + +This sample shows how to call VerifyWithoutCodeAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +NumberVerificationWithoutCodeContent body = new NumberVerificationWithoutCodeContent(new NetworkIdentifier("ipv4", "12.12.12.12"), new Uri("https://www.contoso.com")) +{ + PhoneNumber = "+14424318793", + HashedPhoneNumber = "bwsl", +}; +Response response = await client.VerifyWithoutCodeAsync("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call VerifyWithoutCode. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +NumberVerificationWithoutCodeContent body = new NumberVerificationWithoutCodeContent(new NetworkIdentifier("ipv4", "12.12.12.12"), new Uri("https://www.contoso.com")) +{ + PhoneNumber = "+14424318793", + HashedPhoneNumber = "bwsl", +}; +Response response = client.VerifyWithoutCode("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call VerifyWithoutCodeAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + phoneNumber = "+14424318793", + hashedPhoneNumber = "bwsl", + redirectUri = "https://www.contoso.com", +}); +Response response = await client.VerifyWithoutCodeAsync("zdgrzzaxlodrvewbksn", content); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call VerifyWithoutCode. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + phoneNumber = "+14424318793", + hashedPhoneNumber = "bwsl", + redirectUri = "https://www.contoso.com", +}); +Response response = client.VerifyWithoutCode("zdgrzzaxlodrvewbksn", content); + +Console.WriteLine(response.Status); +]]> + + + +This sample shows how to call VerifyWithCodeAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +NumberVerificationWithCodeContent body = new NumberVerificationWithCodeContent("yn"); +Response response = await client.VerifyWithCodeAsync("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call VerifyWithCode. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +NumberVerificationWithCodeContent body = new NumberVerificationWithCodeContent("yn"); +Response response = client.VerifyWithCode("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call VerifyWithCodeAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + apcCode = "yn", +}); +Response response = await client.VerifyWithCodeAsync("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("verificationResult").ToString()); +]]> + + + +This sample shows how to call VerifyWithCode and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + apcCode = "yn", +}); +Response response = client.VerifyWithCode("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("verificationResult").ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/SimSwap.xml b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/SimSwap.xml new file mode 100644 index 000000000000..d15632cebe83 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Docs/SimSwap.xml @@ -0,0 +1,157 @@ + + + + + +This sample shows how to call RetrieveAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +SimSwapRetrievalContent body = new SimSwapRetrievalContent(new NetworkIdentifier("IPv6", "2001:0db8:85a3:0000:0000:8a2e:0370:7334")) +{ + PhoneNumber = "+61215310263792", +}; +Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call Retrieve. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +SimSwapRetrievalContent body = new SimSwapRetrievalContent(new NetworkIdentifier("IPv6", "2001:0db8:85a3:0000:0000:8a2e:0370:7334")) +{ + PhoneNumber = "+61215310263792", +}; +Response response = client.Retrieve("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call RetrieveAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + phoneNumber = "+61215310263792", + networkIdentifier = new + { + identifierType = "IPv6", + identifier = "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + }, +}); +Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call Retrieve and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + phoneNumber = "+61215310263792", + networkIdentifier = new + { + identifierType = "IPv6", + identifier = "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + }, +}); +Response response = client.Retrieve("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.ToString()); +]]> + + + +This sample shows how to call VerifyAsync. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +SimSwapVerificationContent body = new SimSwapVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12")) +{ + MaxAgeHours = 941, +}; +Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call Verify. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +SimSwapVerificationContent body = new SimSwapVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12")) +{ + MaxAgeHours = 941, +}; +Response response = client.Verify("zdgrzzaxlodrvewbksn", body); +]]> + + + +This sample shows how to call VerifyAsync and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + maxAgeHours = 941, + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, +}); +Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("verificationResult").ToString()); +]]> + + + +This sample shows how to call Verify and parse the result. +"); +TokenCredential credential = new DefaultAzureCredential(); +SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + +using RequestContent content = RequestContent.Create(new +{ + maxAgeHours = 941, + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, +}); +Response response = client.Verify("zdgrzzaxlodrvewbksn", content); + +JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; +Console.WriteLine(result.GetProperty("verificationResult").ToString()); +]]> + + + \ No newline at end of file diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Argument.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Argument.cs new file mode 100644 index 000000000000..8a8fa316d538 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Argument.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + internal static class Argument + { + public static void AssertNotNull(T value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNull(T? value, string name) + where T : struct + { + if (!value.HasValue) + { + throw new ArgumentNullException(name); + } + } + + public static void AssertNotNullOrEmpty(IEnumerable value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value is ICollection collectionOfT && collectionOfT.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + if (value is ICollection collection && collection.Count == 0) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + using IEnumerator e = value.GetEnumerator(); + if (!e.MoveNext()) + { + throw new ArgumentException("Value cannot be an empty collection.", name); + } + } + + public static void AssertNotNullOrEmpty(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (value.Length == 0) + { + throw new ArgumentException("Value cannot be an empty string.", name); + } + } + + public static void AssertNotNullOrWhiteSpace(string value, string name) + { + if (value is null) + { + throw new ArgumentNullException(name); + } + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Value cannot be empty or contain only white-space characters.", name); + } + } + + public static void AssertNotDefault(ref T value, string name) + where T : struct, IEquatable + { + if (value.Equals(default)) + { + throw new ArgumentException("Value cannot be empty.", name); + } + } + + public static void AssertInRange(T value, T minimum, T maximum, string name) + where T : notnull, IComparable + { + if (minimum.CompareTo(value) > 0) + { + throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed."); + } + if (maximum.CompareTo(value) < 0) + { + throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed."); + } + } + + public static void AssertEnumDefined(Type enumType, object value, string name) + { + if (!Enum.IsDefined(enumType, value)) + { + throw new ArgumentException($"Value not defined for {enumType.FullName}.", name); + } + } + + public static T CheckNotNull(T value, string name) + where T : class + { + AssertNotNull(value, name); + return value; + } + + public static string CheckNotNullOrEmpty(string value, string name) + { + AssertNotNullOrEmpty(value, name); + return value; + } + + public static void AssertNull(T value, string name, string message = null) + { + if (value != null) + { + throw new ArgumentException(message ?? "Value must be null.", name); + } + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingDictionary.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingDictionary.cs new file mode 100644 index 000000000000..4e2b60ef6c3c --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingDictionary.cs @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + internal class ChangeTrackingDictionary : IDictionary, IReadOnlyDictionary where TKey : notnull + { + private IDictionary _innerDictionary; + + public ChangeTrackingDictionary() + { + } + + public ChangeTrackingDictionary(IDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(dictionary); + } + + public ChangeTrackingDictionary(IReadOnlyDictionary dictionary) + { + if (dictionary == null) + { + return; + } + _innerDictionary = new Dictionary(); + foreach (var pair in dictionary) + { + _innerDictionary.Add(pair); + } + } + + public bool IsUndefined => _innerDictionary == null; + + public int Count => IsUndefined ? 0 : EnsureDictionary().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureDictionary().IsReadOnly; + + public ICollection Keys => IsUndefined ? Array.Empty() : EnsureDictionary().Keys; + + public ICollection Values => IsUndefined ? Array.Empty() : EnsureDictionary().Values; + + public TValue this[TKey key] + { + get + { + if (IsUndefined) + { + throw new KeyNotFoundException(nameof(key)); + } + return EnsureDictionary()[key]; + } + set + { + EnsureDictionary()[key] = value; + } + } + + IEnumerable IReadOnlyDictionary.Keys => Keys; + + IEnumerable IReadOnlyDictionary.Values => Values; + + public IEnumerator> GetEnumerator() + { + if (IsUndefined) + { + IEnumerator> enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureDictionary().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + EnsureDictionary().Add(item); + } + + public void Clear() + { + EnsureDictionary().Clear(); + } + + public bool Contains(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int index) + { + if (IsUndefined) + { + return; + } + EnsureDictionary().CopyTo(array, index); + } + + public bool Remove(KeyValuePair item) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(item); + } + + public void Add(TKey key, TValue value) + { + EnsureDictionary().Add(key, value); + } + + public bool ContainsKey(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().ContainsKey(key); + } + + public bool Remove(TKey key) + { + if (IsUndefined) + { + return false; + } + return EnsureDictionary().Remove(key); + } + + public bool TryGetValue(TKey key, out TValue value) + { + if (IsUndefined) + { + value = default; + return false; + } + return EnsureDictionary().TryGetValue(key, out value); + } + + public IDictionary EnsureDictionary() + { + return _innerDictionary ??= new Dictionary(); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingList.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingList.cs new file mode 100644 index 000000000000..3c705fe0d23e --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ChangeTrackingList.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Azure.Communication.ProgrammableConnectivity +{ + internal class ChangeTrackingList : IList, IReadOnlyList + { + private IList _innerList; + + public ChangeTrackingList() + { + } + + public ChangeTrackingList(IList innerList) + { + if (innerList != null) + { + _innerList = innerList; + } + } + + public ChangeTrackingList(IReadOnlyList innerList) + { + if (innerList != null) + { + _innerList = innerList.ToList(); + } + } + + public bool IsUndefined => _innerList == null; + + public int Count => IsUndefined ? 0 : EnsureList().Count; + + public bool IsReadOnly => IsUndefined ? false : EnsureList().IsReadOnly; + + public T this[int index] + { + get + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return EnsureList()[index]; + } + set + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList()[index] = value; + } + } + + public void Reset() + { + _innerList = null; + } + + public IEnumerator GetEnumerator() + { + if (IsUndefined) + { + IEnumerator enumerateEmpty() + { + yield break; + } + return enumerateEmpty(); + } + return EnsureList().GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void Add(T item) + { + EnsureList().Add(item); + } + + public void Clear() + { + EnsureList().Clear(); + } + + public bool Contains(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Contains(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (IsUndefined) + { + return; + } + EnsureList().CopyTo(array, arrayIndex); + } + + public bool Remove(T item) + { + if (IsUndefined) + { + return false; + } + return EnsureList().Remove(item); + } + + public int IndexOf(T item) + { + if (IsUndefined) + { + return -1; + } + return EnsureList().IndexOf(item); + } + + public void Insert(int index, T item) + { + EnsureList().Insert(index, item); + } + + public void RemoveAt(int index) + { + if (IsUndefined) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureList().RemoveAt(index); + } + + public IList EnsureList() + { + return _innerList ??= new List(); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ModelSerializationExtensions.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ModelSerializationExtensions.cs new file mode 100644 index 000000000000..7af33bd16416 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/ModelSerializationExtensions.cs @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using System.Xml; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + internal static class ModelSerializationExtensions + { + internal static readonly JsonDocumentOptions JsonDocumentOptions = new JsonDocumentOptions { MaxDepth = 256 }; + internal static readonly ModelReaderWriterOptions WireOptions = new ModelReaderWriterOptions("W"); + + public static object GetObject(this JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.String: + return element.GetString(); + case JsonValueKind.Number: + if (element.TryGetInt32(out int intValue)) + { + return intValue; + } + if (element.TryGetInt64(out long longValue)) + { + return longValue; + } + return element.GetDouble(); + case JsonValueKind.True: + return true; + case JsonValueKind.False: + return false; + case JsonValueKind.Undefined: + case JsonValueKind.Null: + return null; + case JsonValueKind.Object: + var dictionary = new Dictionary(); + foreach (var jsonProperty in element.EnumerateObject()) + { + dictionary.Add(jsonProperty.Name, jsonProperty.Value.GetObject()); + } + return dictionary; + case JsonValueKind.Array: + var list = new List(); + foreach (var item in element.EnumerateArray()) + { + list.Add(item.GetObject()); + } + return list.ToArray(); + default: + throw new NotSupportedException($"Not supported value kind {element.ValueKind}"); + } + } + + public static byte[] GetBytesFromBase64(this JsonElement element, string format) + { + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + + return format switch + { + "U" => TypeFormatters.FromBase64UrlString(element.GetRequiredString()), + "D" => element.GetBytesFromBase64(), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + } + + public static DateTimeOffset GetDateTimeOffset(this JsonElement element, string format) => format switch + { + "U" when element.ValueKind == JsonValueKind.Number => DateTimeOffset.FromUnixTimeSeconds(element.GetInt64()), + _ => TypeFormatters.ParseDateTimeOffset(element.GetString(), format) + }; + + public static TimeSpan GetTimeSpan(this JsonElement element, string format) => TypeFormatters.ParseTimeSpan(element.GetString(), format); + + public static char GetChar(this JsonElement element) + { + if (element.ValueKind == JsonValueKind.String) + { + var text = element.GetString(); + if (text == null || text.Length != 1) + { + throw new NotSupportedException($"Cannot convert \"{text}\" to a char"); + } + return text[0]; + } + else + { + throw new NotSupportedException($"Cannot convert {element.ValueKind} to a char"); + } + } + + [Conditional("DEBUG")] + public static void ThrowNonNullablePropertyIsNull(this JsonProperty property) + { + throw new JsonException($"A property '{property.Name}' defined as non-nullable but received as null from the service. This exception only happens in DEBUG builds of the library and would be ignored in the release build"); + } + + public static string GetRequiredString(this JsonElement element) + { + var value = element.GetString(); + if (value == null) + { + throw new InvalidOperationException($"The requested operation requires an element of type 'String', but the target element has type '{element.ValueKind}'."); + } + return value; + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, DateTime value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, TimeSpan value, string format) + { + writer.WriteStringValue(TypeFormatters.ToString(value, format)); + } + + public static void WriteStringValue(this Utf8JsonWriter writer, char value) + { + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteBase64StringValue(this Utf8JsonWriter writer, byte[] value, string format) + { + if (value == null) + { + writer.WriteNullValue(); + return; + } + switch (format) + { + case "U": + writer.WriteStringValue(TypeFormatters.ToBase64UrlString(value)); + break; + case "D": + writer.WriteBase64StringValue(value); + break; + default: + throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)); + } + } + + public static void WriteNumberValue(this Utf8JsonWriter writer, DateTimeOffset value, string format) + { + if (format != "U") + { + throw new ArgumentOutOfRangeException(nameof(format), "Only 'U' format is supported when writing a DateTimeOffset as a Number."); + } + writer.WriteNumberValue(value.ToUnixTimeSeconds()); + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, T value, ModelReaderWriterOptions options = null) + { + switch (value) + { + case null: + writer.WriteNullValue(); + break; + case IJsonModel jsonModel: + jsonModel.Write(writer, options ?? WireOptions); + break; + case IUtf8JsonSerializable serializable: + serializable.Write(writer); + break; + case byte[] bytes: + writer.WriteBase64StringValue(bytes); + break; + case BinaryData bytes0: + writer.WriteBase64StringValue(bytes0); + break; + case JsonElement json: + json.WriteTo(writer); + break; + case int i: + writer.WriteNumberValue(i); + break; + case decimal d: + writer.WriteNumberValue(d); + break; + case double d0: + if (double.IsNaN(d0)) + { + writer.WriteStringValue("NaN"); + } + else + { + writer.WriteNumberValue(d0); + } + break; + case float f: + writer.WriteNumberValue(f); + break; + case long l: + writer.WriteNumberValue(l); + break; + case string s: + writer.WriteStringValue(s); + break; + case bool b: + writer.WriteBooleanValue(b); + break; + case Guid g: + writer.WriteStringValue(g); + break; + case DateTimeOffset dateTimeOffset: + writer.WriteStringValue(dateTimeOffset, "O"); + break; + case DateTime dateTime: + writer.WriteStringValue(dateTime, "O"); + break; + case IEnumerable> enumerable: + writer.WriteStartObject(); + foreach (var pair in enumerable) + { + writer.WritePropertyName(pair.Key); + writer.WriteObjectValue(pair.Value, options); + } + writer.WriteEndObject(); + break; + case IEnumerable objectEnumerable: + writer.WriteStartArray(); + foreach (var item in objectEnumerable) + { + writer.WriteObjectValue(item, options); + } + writer.WriteEndArray(); + break; + case TimeSpan timeSpan: + writer.WriteStringValue(timeSpan, "P"); + break; + default: + throw new NotSupportedException($"Not supported type {value.GetType()}"); + } + } + + public static void WriteObjectValue(this Utf8JsonWriter writer, object value, ModelReaderWriterOptions options = null) + { + writer.WriteObjectValue(value, options); + } + + internal static class TypeFormatters + { + private const string RoundtripZFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; + public const string DefaultNumberFormat = "G"; + + public static string ToString(bool value) => value ? "true" : "false"; + + public static string ToString(DateTime value, string format) => value.Kind switch + { + DateTimeKind.Utc => ToString((DateTimeOffset)value, format), + _ => throw new NotSupportedException($"DateTime {value} has a Kind of {value.Kind}. Azure SDK requires it to be UTC. You can call DateTime.SpecifyKind to change Kind property value to DateTimeKind.Utc.") + }; + + public static string ToString(DateTimeOffset value, string format) => format switch + { + "D" => value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + "U" => value.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "O" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "o" => value.ToUniversalTime().ToString(RoundtripZFormat, CultureInfo.InvariantCulture), + "R" => value.ToString("r", CultureInfo.InvariantCulture), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(TimeSpan value, string format) => format switch + { + "P" => XmlConvert.ToString(value), + _ => value.ToString(format, CultureInfo.InvariantCulture) + }; + + public static string ToString(byte[] value, string format) => format switch + { + "U" => ToBase64UrlString(value), + "D" => Convert.ToBase64String(value), + _ => throw new ArgumentException($"Format is not supported: '{format}'", nameof(format)) + }; + + public static string ToBase64UrlString(byte[] value) + { + int numWholeOrPartialInputBlocks = checked(value.Length + 2) / 3; + int size = checked(numWholeOrPartialInputBlocks * 4); + char[] output = new char[size]; + + int numBase64Chars = Convert.ToBase64CharArray(value, 0, value.Length, output, 0); + + int i = 0; + for (; i < numBase64Chars; i++) + { + char ch = output[i]; + if (ch == '+') + { + output[i] = '-'; + } + else + { + if (ch == '/') + { + output[i] = '_'; + } + else + { + if (ch == '=') + { + break; + } + } + } + } + + return new string(output, 0, i); + } + + public static byte[] FromBase64UrlString(string value) + { + int paddingCharsToAdd = (value.Length % 4) switch + { + 0 => 0, + 2 => 2, + 3 => 1, + _ => throw new InvalidOperationException("Malformed input") + }; + char[] output = new char[(value.Length + paddingCharsToAdd)]; + int i = 0; + for (; i < value.Length; i++) + { + char ch = value[i]; + if (ch == '-') + { + output[i] = '+'; + } + else + { + if (ch == '_') + { + output[i] = '/'; + } + else + { + output[i] = ch; + } + } + } + + for (; i < output.Length; i++) + { + output[i] = '='; + } + + return Convert.FromBase64CharArray(output, 0, output.Length); + } + + public static DateTimeOffset ParseDateTimeOffset(string value, string format) => format switch + { + "U" => DateTimeOffset.FromUnixTimeSeconds(long.Parse(value, CultureInfo.InvariantCulture)), + _ => DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal) + }; + + public static TimeSpan ParseTimeSpan(string value, string format) => format switch + { + "P" => XmlConvert.ToTimeSpan(value), + _ => TimeSpan.ParseExact(value, format, CultureInfo.InvariantCulture) + }; + + public static string ConvertToString(object value, string format = null) => value switch + { + null => "null", + string s => s, + bool b => ToString(b), + int or float or double or long or decimal => ((IFormattable)value).ToString(DefaultNumberFormat, CultureInfo.InvariantCulture), + byte[] b0 when format != null => ToString(b0, format), + IEnumerable s0 => string.Join(",", s0), + DateTimeOffset dateTime when format != null => ToString(dateTime, format), + TimeSpan timeSpan when format != null => ToString(timeSpan, format), + TimeSpan timeSpan0 => XmlConvert.ToString(timeSpan0), + Guid guid => guid.ToString(), + BinaryData binaryData => ConvertToString(binaryData.ToArray(), format), + _ => value.ToString() + }; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Optional.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Optional.cs new file mode 100644 index 000000000000..86bcb20f00fa --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Optional.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.Collections.Generic; +using System.Text.Json; + +namespace Azure.Communication.ProgrammableConnectivity +{ + internal static class Optional + { + public static bool IsCollectionDefined(IEnumerable collection) + { + return !(collection is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined); + } + + public static bool IsCollectionDefined(IDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsCollectionDefined(IReadOnlyDictionary collection) + { + return !(collection is ChangeTrackingDictionary changeTrackingDictionary && changeTrackingDictionary.IsUndefined); + } + + public static bool IsDefined(T? value) + where T : struct + { + return value.HasValue; + } + + public static bool IsDefined(object value) + { + return value != null; + } + + public static bool IsDefined(JsonElement value) + { + return value.ValueKind != JsonValueKind.Undefined; + } + + public static bool IsDefined(string value) + { + return value != null; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Utf8JsonRequestContent.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Utf8JsonRequestContent.cs new file mode 100644 index 000000000000..35b5d8cb1785 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Internal/Utf8JsonRequestContent.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + internal class Utf8JsonRequestContent : RequestContent + { + private readonly MemoryStream _stream; + private readonly RequestContent _content; + + public Utf8JsonRequestContent() + { + _stream = new MemoryStream(); + _content = Create(_stream); + JsonWriter = new Utf8JsonWriter(_stream); + } + + public Utf8JsonWriter JsonWriter { get; } + + public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default) + { + await JsonWriter.FlushAsync().ConfigureAwait(false); + await _content.WriteToAsync(stream, cancellationToken).ConfigureAwait(false); + } + + public override void WriteTo(Stream stream, CancellationToken cancellationToken = default) + { + JsonWriter.Flush(); + _content.WriteTo(stream, cancellationToken); + } + + public override bool TryComputeLength(out long length) + { + length = JsonWriter.BytesCommitted + JsonWriter.BytesPending; + return true; + } + + public override void Dispose() + { + JsonWriter.Dispose(); + _content.Dispose(); + _stream.Dispose(); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.Serialization.cs new file mode 100644 index 000000000000..12f5d7a65380 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class Ipv4Address : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Ipv4Address)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("ipv4"u8); + writer.WriteStringValue(Ipv4); + writer.WritePropertyName("port"u8); + writer.WriteNumberValue(Port); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Ipv4Address IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Ipv4Address)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeIpv4Address(document.RootElement, options); + } + + internal static Ipv4Address DeserializeIpv4Address(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string ipv4 = default; + int port = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ipv4"u8)) + { + ipv4 = property.Value.GetString(); + continue; + } + if (property.NameEquals("port"u8)) + { + port = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Ipv4Address(ipv4, port, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Ipv4Address)} does not support writing '{options.Format}' format."); + } + } + + Ipv4Address IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeIpv4Address(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Ipv4Address)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Ipv4Address FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeIpv4Address(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.cs new file mode 100644 index 000000000000..8ec205ddbc0e --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv4Address.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// IPv4 device indicator. + public partial class Ipv4Address + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// An IPv4 address. This may be specified as an exact address, or as a subnet in CIDR notation. + /// User equipment port. + /// is null. + public Ipv4Address(string ipv4, int port) + { + Argument.AssertNotNull(ipv4, nameof(ipv4)); + + Ipv4 = ipv4; + Port = port; + } + + /// Initializes a new instance of . + /// An IPv4 address. This may be specified as an exact address, or as a subnet in CIDR notation. + /// User equipment port. + /// Keeps track of any properties unknown to the library. + internal Ipv4Address(string ipv4, int port, IDictionary serializedAdditionalRawData) + { + Ipv4 = ipv4; + Port = port; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Ipv4Address() + { + } + + /// An IPv4 address. This may be specified as an exact address, or as a subnet in CIDR notation. + public string Ipv4 { get; } + /// User equipment port. + public int Port { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.Serialization.cs new file mode 100644 index 000000000000..ccb47bafdedd --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class Ipv6Address : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Ipv6Address)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("ipv6"u8); + writer.WriteStringValue(Ipv6); + writer.WritePropertyName("port"u8); + writer.WriteNumberValue(Port); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + Ipv6Address IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(Ipv6Address)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeIpv6Address(document.RootElement, options); + } + + internal static Ipv6Address DeserializeIpv6Address(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string ipv6 = default; + int port = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("ipv6"u8)) + { + ipv6 = property.Value.GetString(); + continue; + } + if (property.NameEquals("port"u8)) + { + port = property.Value.GetInt32(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new Ipv6Address(ipv6, port, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(Ipv6Address)} does not support writing '{options.Format}' format."); + } + } + + Ipv6Address IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeIpv6Address(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(Ipv6Address)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static Ipv6Address FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeIpv6Address(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.cs new file mode 100644 index 000000000000..633f96886041 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/Ipv6Address.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// IPv6 device indicator. + public partial class Ipv6Address + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// An IPv6 address. This may be specified as an exact address, or as a subnet in CIDR notation. + /// User equipment port. + /// is null. + public Ipv6Address(string ipv6, int port) + { + Argument.AssertNotNull(ipv6, nameof(ipv6)); + + Ipv6 = ipv6; + Port = port; + } + + /// Initializes a new instance of . + /// An IPv6 address. This may be specified as an exact address, or as a subnet in CIDR notation. + /// User equipment port. + /// Keeps track of any properties unknown to the library. + internal Ipv6Address(string ipv6, int port, IDictionary serializedAdditionalRawData) + { + Ipv6 = ipv6; + Port = port; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal Ipv6Address() + { + } + + /// An IPv6 address. This may be specified as an exact address, or as a subnet in CIDR notation. + public string Ipv6 { get; } + /// User equipment port. + public int Port { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.Serialization.cs new file mode 100644 index 000000000000..89ef4b6e9e76 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.Serialization.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class LocationDevice : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LocationDevice)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(NetworkAccessIdentifier)) + { + writer.WritePropertyName("networkAccessIdentifier"u8); + writer.WriteStringValue(NetworkAccessIdentifier); + } + if (Optional.IsDefined(PhoneNumber)) + { + writer.WritePropertyName("phoneNumber"u8); + writer.WriteStringValue(PhoneNumber); + } + if (Optional.IsDefined(Ipv4Address)) + { + writer.WritePropertyName("ipv4Address"u8); + writer.WriteObjectValue(Ipv4Address, options); + } + if (Optional.IsDefined(Ipv6Address)) + { + writer.WritePropertyName("ipv6Address"u8); + writer.WriteObjectValue(Ipv6Address, options); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + LocationDevice IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(LocationDevice)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeLocationDevice(document.RootElement, options); + } + + internal static LocationDevice DeserializeLocationDevice(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string networkAccessIdentifier = default; + string phoneNumber = default; + Ipv4Address ipv4Address = default; + Ipv6Address ipv6Address = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("networkAccessIdentifier"u8)) + { + networkAccessIdentifier = property.Value.GetString(); + continue; + } + if (property.NameEquals("phoneNumber"u8)) + { + phoneNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("ipv4Address"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + ipv4Address = Ipv4Address.DeserializeIpv4Address(property.Value, options); + continue; + } + if (property.NameEquals("ipv6Address"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + ipv6Address = Ipv6Address.DeserializeIpv6Address(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new LocationDevice(networkAccessIdentifier, phoneNumber, ipv4Address, ipv6Address, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(LocationDevice)} does not support writing '{options.Format}' format."); + } + } + + LocationDevice IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLocationDevice(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(LocationDevice)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static LocationDevice FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeLocationDevice(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.cs new file mode 100644 index 000000000000..6748649f211b --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/LocationDevice.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Device information needed by operator to provide location information. Include exactly one of these properties to identify your device. + public partial class LocationDevice + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public LocationDevice() + { + } + + /// Initializes a new instance of . + /// External identifier or network access identifier of the device. + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + /// The Ipv4 address. + /// The Ipv6 address. + /// Keeps track of any properties unknown to the library. + internal LocationDevice(string networkAccessIdentifier, string phoneNumber, Ipv4Address ipv4Address, Ipv6Address ipv6Address, IDictionary serializedAdditionalRawData) + { + NetworkAccessIdentifier = networkAccessIdentifier; + PhoneNumber = phoneNumber; + Ipv4Address = ipv4Address; + Ipv6Address = ipv6Address; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// External identifier or network access identifier of the device. + public string NetworkAccessIdentifier { get; set; } + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + public string PhoneNumber { get; set; } + /// The Ipv4 address. + public Ipv4Address Ipv4Address { get; set; } + /// The Ipv6 address. + public Ipv6Address Ipv6Address { get; set; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.Serialization.cs new file mode 100644 index 000000000000..2f5694d976cf --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.Serialization.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class NetworkIdentifier : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NetworkIdentifier)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("identifierType"u8); + writer.WriteStringValue(IdentifierType); + writer.WritePropertyName("identifier"u8); + writer.WriteStringValue(Identifier); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NetworkIdentifier IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NetworkIdentifier)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNetworkIdentifier(document.RootElement, options); + } + + internal static NetworkIdentifier DeserializeNetworkIdentifier(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string identifierType = default; + string identifier = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("identifierType"u8)) + { + identifierType = property.Value.GetString(); + continue; + } + if (property.NameEquals("identifier"u8)) + { + identifier = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NetworkIdentifier(identifierType, identifier, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NetworkIdentifier)} does not support writing '{options.Format}' format."); + } + } + + NetworkIdentifier IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNetworkIdentifier(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NetworkIdentifier)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NetworkIdentifier FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNetworkIdentifier(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.cs new file mode 100644 index 000000000000..0c9d7c39686c --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkIdentifier.cs @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Identifier for the network to be queried. + public partial class NetworkIdentifier + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The type of identifier for the network. one of: 'IPv4', 'IPv6', 'MSISDN', 'NetworkCode'. + /// + /// The network identifier, based on the identifierType: an IPv4 address, an IPv6 address, an MSISDN, or a Network Code. + /// A Network Code may be obtained from APC documentation or from the APC /Network:retrieve endpoint. + /// + /// or is null. + public NetworkIdentifier(string identifierType, string identifier) + { + Argument.AssertNotNull(identifierType, nameof(identifierType)); + Argument.AssertNotNull(identifier, nameof(identifier)); + + IdentifierType = identifierType; + Identifier = identifier; + } + + /// Initializes a new instance of . + /// The type of identifier for the network. one of: 'IPv4', 'IPv6', 'MSISDN', 'NetworkCode'. + /// + /// The network identifier, based on the identifierType: an IPv4 address, an IPv6 address, an MSISDN, or a Network Code. + /// A Network Code may be obtained from APC documentation or from the APC /Network:retrieve endpoint. + /// + /// Keeps track of any properties unknown to the library. + internal NetworkIdentifier(string identifierType, string identifier, IDictionary serializedAdditionalRawData) + { + IdentifierType = identifierType; + Identifier = identifier; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NetworkIdentifier() + { + } + + /// The type of identifier for the network. one of: 'IPv4', 'IPv6', 'MSISDN', 'NetworkCode'. + public string IdentifierType { get; } + /// + /// The network identifier, based on the identifierType: an IPv4 address, an IPv6 address, an MSISDN, or a Network Code. + /// A Network Code may be obtained from APC documentation or from the APC /Network:retrieve endpoint. + /// + public string Identifier { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.Serialization.cs new file mode 100644 index 000000000000..0593c3ed0fa3 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class NetworkRetrievalResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NetworkRetrievalResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("networkCode"u8); + writer.WriteStringValue(NetworkCode); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NetworkRetrievalResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NetworkRetrievalResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNetworkRetrievalResult(document.RootElement, options); + } + + internal static NetworkRetrievalResult DeserializeNetworkRetrievalResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string networkCode = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("networkCode"u8)) + { + networkCode = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NetworkRetrievalResult(networkCode, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NetworkRetrievalResult)} does not support writing '{options.Format}' format."); + } + } + + NetworkRetrievalResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNetworkRetrievalResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NetworkRetrievalResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NetworkRetrievalResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNetworkRetrievalResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.cs new file mode 100644 index 000000000000..5c6e83c30533 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NetworkRetrievalResult.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// The network that the device is on. + public partial class NetworkRetrievalResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The identifier for the network. This can be used as the networkIdentifier for the service APIs. + /// is null. + internal NetworkRetrievalResult(string networkCode) + { + Argument.AssertNotNull(networkCode, nameof(networkCode)); + + NetworkCode = networkCode; + } + + /// Initializes a new instance of . + /// The identifier for the network. This can be used as the networkIdentifier for the service APIs. + /// Keeps track of any properties unknown to the library. + internal NetworkRetrievalResult(string networkCode, IDictionary serializedAdditionalRawData) + { + NetworkCode = networkCode; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NetworkRetrievalResult() + { + } + + /// The identifier for the network. This can be used as the networkIdentifier for the service APIs. + public string NetworkCode { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerification.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerification.cs new file mode 100644 index 000000000000..19e87e8c27f6 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerification.cs @@ -0,0 +1,347 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Communication.ProgrammableConnectivity +{ + // Data plane generated sub-client. + /// + /// Number operations include Frontend Authentication. + /// + /// Users first make a call to the endpoint /Number:verify, which returns a redirect to the device's + /// Network. This is followed by the device to authenticate directly with the Network. The Network + /// responds with a token and a redirect. This token can be exchanged with APC for a code. + /// + /// Users make a second call to the endpoint /Number:verify including the code. The code is used + /// to verify the device number. The second response is a 200 containing the result of the query. + /// + /// For more information on the steps required to use Number Verificaiton, see the APC documentation. + /// + public partial class NumberVerification + { + private static readonly string[] AuthorizationScopes = new string[] { "https://management.azure.com//.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of NumberVerification for mocking. + protected NumberVerification() + { + } + + /// Initializes a new instance of NumberVerification. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// An Azure Programmable Connectivity Endpoint providing access to Network APIs, for example https://{region}.apcgatewayapi.azure.com. + /// The API version to use for this operation. + internal NumberVerification(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Verifies the phone number (MSISDN) associated with a device. As part of the frontend authorization flow, the device is redirected to the operator network to authenticate directly. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task VerifyWithoutCodeAsync(string apcGatewayId, NumberVerificationWithoutCodeContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await VerifyWithoutCodeAsync(apcGatewayId, content, context).ConfigureAwait(false); + return response; + } + + /// Verifies the phone number (MSISDN) associated with a device. As part of the frontend authorization flow, the device is redirected to the operator network to authenticate directly. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual Response VerifyWithoutCode(string apcGatewayId, NumberVerificationWithoutCodeContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = VerifyWithoutCode(apcGatewayId, content, context); + return response; + } + + /// + /// [Protocol Method] Verifies the phone number (MSISDN) associated with a device. As part of the frontend authorization flow, the device is redirected to the operator network to authenticate directly. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task VerifyWithoutCodeAsync(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("NumberVerification.VerifyWithoutCode"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyWithoutCodeRequest(apcGatewayId, content, context); + RedirectPolicy.SetAllowAutoRedirect(message, true); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Verifies the phone number (MSISDN) associated with a device. As part of the frontend authorization flow, the device is redirected to the operator network to authenticate directly. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response VerifyWithoutCode(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("NumberVerification.VerifyWithoutCode"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyWithoutCodeRequest(apcGatewayId, content, context); + RedirectPolicy.SetAllowAutoRedirect(message, true); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Verifies the phone number (MSISDN) associated with a device. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task> VerifyWithCodeAsync(string apcGatewayId, NumberVerificationWithCodeContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await VerifyWithCodeAsync(apcGatewayId, content, context).ConfigureAwait(false); + return Response.FromValue(NumberVerificationResult.FromResponse(response), response); + } + + /// Verifies the phone number (MSISDN) associated with a device. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual Response VerifyWithCode(string apcGatewayId, NumberVerificationWithCodeContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = VerifyWithCode(apcGatewayId, content, context); + return Response.FromValue(NumberVerificationResult.FromResponse(response), response); + } + + /// + /// [Protocol Method] Verifies the phone number (MSISDN) associated with a device. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task VerifyWithCodeAsync(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("NumberVerification.VerifyWithCode"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyWithCodeRequest(apcGatewayId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Verifies the phone number (MSISDN) associated with a device. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response VerifyWithCode(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("NumberVerification.VerifyWithCode"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyWithCodeRequest(apcGatewayId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateVerifyWithoutCodeRequest(string apcGatewayId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier302); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/number-verification/number:verify", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("apc-gateway-id", apcGatewayId); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateVerifyWithCodeRequest(string apcGatewayId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/number-verification/number:verify", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("apc-gateway-id", apcGatewayId); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier302; + private static ResponseClassifier ResponseClassifier302 => _responseClassifier302 ??= new StatusCodeClassifier(stackalloc ushort[] { 302 }); + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.Serialization.cs new file mode 100644 index 000000000000..b72bc91014a2 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class NumberVerificationResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberVerificationResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("verificationResult"u8); + writer.WriteBooleanValue(VerificationResult); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberVerificationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberVerificationResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberVerificationResult(document.RootElement, options); + } + + internal static NumberVerificationResult DeserializeNumberVerificationResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool verificationResult = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("verificationResult"u8)) + { + verificationResult = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberVerificationResult(verificationResult, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberVerificationResult)} does not support writing '{options.Format}' format."); + } + } + + NumberVerificationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberVerificationResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberVerificationResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberVerificationResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberVerificationResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.cs new file mode 100644 index 000000000000..eb64683bbfcf --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Response verifying number of device. + public partial class NumberVerificationResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// True if number if the phone number matches the device, False otherwise. + internal NumberVerificationResult(bool verificationResult) + { + VerificationResult = verificationResult; + } + + /// Initializes a new instance of . + /// True if number if the phone number matches the device, False otherwise. + /// Keeps track of any properties unknown to the library. + internal NumberVerificationResult(bool verificationResult, IDictionary serializedAdditionalRawData) + { + VerificationResult = verificationResult; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NumberVerificationResult() + { + } + + /// True if number if the phone number matches the device, False otherwise. + public bool VerificationResult { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.Serialization.cs new file mode 100644 index 000000000000..4040bf281ead --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class NumberVerificationWithCodeContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberVerificationWithCodeContent)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("apcCode"u8); + writer.WriteStringValue(ApcCode); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberVerificationWithCodeContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberVerificationWithCodeContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberVerificationWithCodeContent(document.RootElement, options); + } + + internal static NumberVerificationWithCodeContent DeserializeNumberVerificationWithCodeContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string apcCode = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("apcCode"u8)) + { + apcCode = property.Value.GetString(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberVerificationWithCodeContent(apcCode, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberVerificationWithCodeContent)} does not support writing '{options.Format}' format."); + } + } + + NumberVerificationWithCodeContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberVerificationWithCodeContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberVerificationWithCodeContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberVerificationWithCodeContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberVerificationWithCodeContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.cs new file mode 100644 index 000000000000..14409d3fc5c0 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithCodeContent.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Request to verify number of device - second call. + public partial class NumberVerificationWithCodeContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// The code provided by APC in exchange for the operator code. + /// is null. + public NumberVerificationWithCodeContent(string apcCode) + { + Argument.AssertNotNull(apcCode, nameof(apcCode)); + + ApcCode = apcCode; + } + + /// Initializes a new instance of . + /// The code provided by APC in exchange for the operator code. + /// Keeps track of any properties unknown to the library. + internal NumberVerificationWithCodeContent(string apcCode, IDictionary serializedAdditionalRawData) + { + ApcCode = apcCode; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NumberVerificationWithCodeContent() + { + } + + /// The code provided by APC in exchange for the operator code. + public string ApcCode { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.Serialization.cs new file mode 100644 index 000000000000..501007f3c02c --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.Serialization.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class NumberVerificationWithoutCodeContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberVerificationWithoutCodeContent)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("networkIdentifier"u8); + writer.WriteObjectValue(NetworkIdentifier, options); + if (Optional.IsDefined(PhoneNumber)) + { + writer.WritePropertyName("phoneNumber"u8); + writer.WriteStringValue(PhoneNumber); + } + if (Optional.IsDefined(HashedPhoneNumber)) + { + writer.WritePropertyName("hashedPhoneNumber"u8); + writer.WriteStringValue(HashedPhoneNumber); + } + writer.WritePropertyName("redirectUri"u8); + writer.WriteStringValue(RedirectUri.AbsoluteUri); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + NumberVerificationWithoutCodeContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(NumberVerificationWithoutCodeContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeNumberVerificationWithoutCodeContent(document.RootElement, options); + } + + internal static NumberVerificationWithoutCodeContent DeserializeNumberVerificationWithoutCodeContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + NetworkIdentifier networkIdentifier = default; + string phoneNumber = default; + string hashedPhoneNumber = default; + Uri redirectUri = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("networkIdentifier"u8)) + { + networkIdentifier = NetworkIdentifier.DeserializeNetworkIdentifier(property.Value, options); + continue; + } + if (property.NameEquals("phoneNumber"u8)) + { + phoneNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("hashedPhoneNumber"u8)) + { + hashedPhoneNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("redirectUri"u8)) + { + redirectUri = new Uri(property.Value.GetString()); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new NumberVerificationWithoutCodeContent(networkIdentifier, phoneNumber, hashedPhoneNumber, redirectUri, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(NumberVerificationWithoutCodeContent)} does not support writing '{options.Format}' format."); + } + } + + NumberVerificationWithoutCodeContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberVerificationWithoutCodeContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(NumberVerificationWithoutCodeContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static NumberVerificationWithoutCodeContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeNumberVerificationWithoutCodeContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.cs new file mode 100644 index 000000000000..28dfa4af54fb --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/NumberVerificationWithoutCodeContent.cs @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Request to verify number of device - first call. + public partial class NumberVerificationWithoutCodeContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Identifier for the network to query for this device. + /// Redirect URI to backend application. + /// or is null. + public NumberVerificationWithoutCodeContent(NetworkIdentifier networkIdentifier, Uri redirectUri) + { + Argument.AssertNotNull(networkIdentifier, nameof(networkIdentifier)); + Argument.AssertNotNull(redirectUri, nameof(redirectUri)); + + NetworkIdentifier = networkIdentifier; + RedirectUri = redirectUri; + } + + /// Initializes a new instance of . + /// Identifier for the network to query for this device. + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + /// Hashed phone number. SHA-256 (in hexadecimal representation) of the mobile phone number in **E.164 format (starting with country code)**. Optionally prefixed with '+'. + /// Redirect URI to backend application. + /// Keeps track of any properties unknown to the library. + internal NumberVerificationWithoutCodeContent(NetworkIdentifier networkIdentifier, string phoneNumber, string hashedPhoneNumber, Uri redirectUri, IDictionary serializedAdditionalRawData) + { + NetworkIdentifier = networkIdentifier; + PhoneNumber = phoneNumber; + HashedPhoneNumber = hashedPhoneNumber; + RedirectUri = redirectUri; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal NumberVerificationWithoutCodeContent() + { + } + + /// Identifier for the network to query for this device. + public NetworkIdentifier NetworkIdentifier { get; } + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + public string PhoneNumber { get; set; } + /// Hashed phone number. SHA-256 (in hexadecimal representation) of the mobile phone number in **E.164 format (starting with country code)**. Optionally prefixed with '+'. + public string HashedPhoneNumber { get; set; } + /// Redirect URI to backend application. + public Uri RedirectUri { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClient.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClient.cs new file mode 100644 index 000000000000..78178e8158db --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClient.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Communication.ProgrammableConnectivity +{ + // Data plane generated client. + /// Azure Programmable Connectivity (APC) provides a unified interface to the Network APIs of multiple Telecom Operators. Note that Operators may deprecate a Network API with less advance notice than the Azure standard, in which case APC will also deprecate that Network API. + public partial class ProgrammableConnectivityClient + { + private static readonly string[] AuthorizationScopes = new string[] { "https://management.azure.com//.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of ProgrammableConnectivityClient for mocking. + protected ProgrammableConnectivityClient() + { + } + + /// Initializes a new instance of ProgrammableConnectivityClient. + /// An Azure Programmable Connectivity Endpoint providing access to Network APIs, for example https://{region}.apcgatewayapi.azure.com. + /// A credential used to authenticate to an Azure Service. + /// or is null. + public ProgrammableConnectivityClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new ProgrammableConnectivityClientOptions()) + { + } + + /// Initializes a new instance of ProgrammableConnectivityClient. + /// An Azure Programmable Connectivity Endpoint providing access to Network APIs, for example https://{region}.apcgatewayapi.azure.com. + /// A credential used to authenticate to an Azure Service. + /// The options for configuring the client. + /// or is null. + public ProgrammableConnectivityClient(Uri endpoint, TokenCredential credential, ProgrammableConnectivityClientOptions options) + { + Argument.AssertNotNull(endpoint, nameof(endpoint)); + Argument.AssertNotNull(credential, nameof(credential)); + options ??= new ProgrammableConnectivityClientOptions(); + + ClientDiagnostics = new ClientDiagnostics(options, true); + _tokenCredential = credential; + _pipeline = HttpPipelineBuilder.Build(options, Array.Empty(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); + _endpoint = endpoint; + } + + /// Initializes a new instance of DeviceLocation. + /// The API version to use for this operation. + /// is null. + public virtual DeviceLocation GetDeviceLocationClient(string apiVersion = "2024-02-09-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new DeviceLocation(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of DeviceNetwork. + /// The API version to use for this operation. + /// is null. + public virtual DeviceNetwork GetDeviceNetworkClient(string apiVersion = "2024-02-09-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new DeviceNetwork(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of NumberVerification. + /// The API version to use for this operation. + /// is null. + public virtual NumberVerification GetNumberVerificationClient(string apiVersion = "2024-02-09-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new NumberVerification(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, apiVersion); + } + + /// Initializes a new instance of SimSwap. + /// The API version to use for this operation. + /// is null. + public virtual SimSwap GetSimSwapClient(string apiVersion = "2024-02-09-preview") + { + Argument.AssertNotNull(apiVersion, nameof(apiVersion)); + + return new SimSwap(ClientDiagnostics, _pipeline, _tokenCredential, _endpoint, apiVersion); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClientOptions.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClientOptions.cs new file mode 100644 index 000000000000..f502d00b4e97 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/ProgrammableConnectivityClientOptions.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Client options for ProgrammableConnectivityClient. + public partial class ProgrammableConnectivityClientOptions : ClientOptions + { + private const ServiceVersion LatestVersion = ServiceVersion.V2024_02_09_Preview; + + /// The version of the service to use. + public enum ServiceVersion + { + /// Service version "2024-02-09-preview". + V2024_02_09_Preview = 1, + } + + internal string Version { get; } + + /// Initializes new instance of ProgrammableConnectivityClientOptions. + public ProgrammableConnectivityClientOptions(ServiceVersion version = LatestVersion) + { + Version = version switch + { + ServiceVersion.V2024_02_09_Preview => "2024-02-09-preview", + _ => throw new NotSupportedException() + }; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwap.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwap.cs new file mode 100644 index 000000000000..c8696bdccb13 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwap.cs @@ -0,0 +1,332 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace Azure.Communication.ProgrammableConnectivity +{ + // Data plane generated sub-client. + /// SIM Swap API provides the customer the ability to obtain information on any recent SIM pairing change related to the User's mobile account. + public partial class SimSwap + { + private static readonly string[] AuthorizationScopes = new string[] { "https://management.azure.com//.default" }; + private readonly TokenCredential _tokenCredential; + private readonly HttpPipeline _pipeline; + private readonly Uri _endpoint; + private readonly string _apiVersion; + + /// The ClientDiagnostics is used to provide tracing support for the client library. + internal ClientDiagnostics ClientDiagnostics { get; } + + /// The HTTP pipeline for sending and receiving REST requests and responses. + public virtual HttpPipeline Pipeline => _pipeline; + + /// Initializes a new instance of SimSwap for mocking. + protected SimSwap() + { + } + + /// Initializes a new instance of SimSwap. + /// The handler for diagnostic messaging in the client. + /// The HTTP pipeline for sending and receiving REST requests and responses. + /// The token credential to copy. + /// An Azure Programmable Connectivity Endpoint providing access to Network APIs, for example https://{region}.apcgatewayapi.azure.com. + /// The API version to use for this operation. + internal SimSwap(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, TokenCredential tokenCredential, Uri endpoint, string apiVersion) + { + ClientDiagnostics = clientDiagnostics; + _pipeline = pipeline; + _tokenCredential = tokenCredential; + _endpoint = endpoint; + _apiVersion = apiVersion; + } + + /// Provides timestamp of latest SIM swap. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task> RetrieveAsync(string apcGatewayId, SimSwapRetrievalContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await RetrieveAsync(apcGatewayId, content, context).ConfigureAwait(false); + return Response.FromValue(SimSwapRetrievalResult.FromResponse(response), response); + } + + /// Provides timestamp of latest SIM swap. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual Response Retrieve(string apcGatewayId, SimSwapRetrievalContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Retrieve(apcGatewayId, content, context); + return Response.FromValue(SimSwapRetrievalResult.FromResponse(response), response); + } + + /// + /// [Protocol Method] Provides timestamp of latest SIM swap + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task RetrieveAsync(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SimSwap.Retrieve"); + scope.Start(); + try + { + using HttpMessage message = CreateRetrieveRequest(apcGatewayId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Provides timestamp of latest SIM swap + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Retrieve(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SimSwap.Retrieve"); + scope.Start(); + try + { + using HttpMessage message = CreateRetrieveRequest(apcGatewayId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// Verifies if a SIM swap has been performed during a past period (defined in the request with 'maxAgeHours' attribute). Returns 'True' if a SIM swap has occured. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual async Task> VerifyAsync(string apcGatewayId, SimSwapVerificationContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = await VerifyAsync(apcGatewayId, content, context).ConfigureAwait(false); + return Response.FromValue(SimSwapVerificationResult.FromResponse(response), response); + } + + /// Verifies if a SIM swap has been performed during a past period (defined in the request with 'maxAgeHours' attribute). Returns 'True' if a SIM swap has occured. + /// The identifier of the APC Gateway resource which should handle this request. + /// Body parameter. + /// The cancellation token to use. + /// or is null. + /// + public virtual Response Verify(string apcGatewayId, SimSwapVerificationContent body, CancellationToken cancellationToken = default) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(body, nameof(body)); + + using RequestContent content = body.ToRequestContent(); + RequestContext context = FromCancellationToken(cancellationToken); + Response response = Verify(apcGatewayId, content, context); + return Response.FromValue(SimSwapVerificationResult.FromResponse(response), response); + } + + /// + /// [Protocol Method] Verifies if a SIM swap has been performed during a past period (defined in the request with 'maxAgeHours' attribute). Returns 'True' if a SIM swap has occured. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual async Task VerifyAsync(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SimSwap.Verify"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyRequest(apcGatewayId, content, context); + return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + /// + /// [Protocol Method] Verifies if a SIM swap has been performed during a past period (defined in the request with 'maxAgeHours' attribute). Returns 'True' if a SIM swap has occured. + /// + /// + /// + /// This protocol method allows explicit creation of the request and processing of the response for advanced scenarios. + /// + /// + /// + /// + /// Please try the simpler convenience overload with strongly typed models first. + /// + /// + /// + /// + /// The identifier of the APC Gateway resource which should handle this request. + /// The content to send as the body of the request. + /// The request context, which can override default behaviors of the client pipeline on a per-call basis. + /// or is null. + /// Service returned a non-success status code. + /// The response returned from the service. + /// + public virtual Response Verify(string apcGatewayId, RequestContent content, RequestContext context = null) + { + Argument.AssertNotNull(apcGatewayId, nameof(apcGatewayId)); + Argument.AssertNotNull(content, nameof(content)); + + using var scope = ClientDiagnostics.CreateScope("SimSwap.Verify"); + scope.Start(); + try + { + using HttpMessage message = CreateVerifyRequest(apcGatewayId, content, context); + return _pipeline.ProcessMessage(message, context); + } + catch (Exception e) + { + scope.Failed(e); + throw; + } + } + + internal HttpMessage CreateRetrieveRequest(string apcGatewayId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/sim-swap/sim-swap:retrieve", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("apc-gateway-id", apcGatewayId); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + internal HttpMessage CreateVerifyRequest(string apcGatewayId, RequestContent content, RequestContext context) + { + var message = _pipeline.CreateMessage(context, ResponseClassifier200); + var request = message.Request; + request.Method = RequestMethod.Post; + var uri = new RawRequestUriBuilder(); + uri.Reset(_endpoint); + uri.AppendPath("/sim-swap/sim-swap:verify", false); + uri.AppendQuery("api-version", _apiVersion, true); + request.Uri = uri; + request.Headers.Add("apc-gateway-id", apcGatewayId); + request.Headers.Add("Accept", "application/json"); + request.Headers.Add("Content-Type", "application/json"); + request.Content = content; + return message; + } + + private static RequestContext DefaultRequestContext = new RequestContext(); + internal static RequestContext FromCancellationToken(CancellationToken cancellationToken = default) + { + if (!cancellationToken.CanBeCanceled) + { + return DefaultRequestContext; + } + + return new RequestContext() { CancellationToken = cancellationToken }; + } + + private static ResponseClassifier _responseClassifier200; + private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.Serialization.cs new file mode 100644 index 000000000000..8ffdbca28bad --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.Serialization.cs @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class SimSwapRetrievalContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapRetrievalContent)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(PhoneNumber)) + { + writer.WritePropertyName("phoneNumber"u8); + writer.WriteStringValue(PhoneNumber); + } + writer.WritePropertyName("networkIdentifier"u8); + writer.WriteObjectValue(NetworkIdentifier, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SimSwapRetrievalContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapRetrievalContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSimSwapRetrievalContent(document.RootElement, options); + } + + internal static SimSwapRetrievalContent DeserializeSimSwapRetrievalContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string phoneNumber = default; + NetworkIdentifier networkIdentifier = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("phoneNumber"u8)) + { + phoneNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("networkIdentifier"u8)) + { + networkIdentifier = NetworkIdentifier.DeserializeNetworkIdentifier(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SimSwapRetrievalContent(phoneNumber, networkIdentifier, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SimSwapRetrievalContent)} does not support writing '{options.Format}' format."); + } + } + + SimSwapRetrievalContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapRetrievalContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SimSwapRetrievalContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SimSwapRetrievalContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapRetrievalContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.cs new file mode 100644 index 000000000000..7a2b28d912fa --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalContent.cs @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Request to retrieve SimSwap date. + public partial class SimSwapRetrievalContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Network to query for this device. + /// is null. + public SimSwapRetrievalContent(NetworkIdentifier networkIdentifier) + { + Argument.AssertNotNull(networkIdentifier, nameof(networkIdentifier)); + + NetworkIdentifier = networkIdentifier; + } + + /// Initializes a new instance of . + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + /// Network to query for this device. + /// Keeps track of any properties unknown to the library. + internal SimSwapRetrievalContent(string phoneNumber, NetworkIdentifier networkIdentifier, IDictionary serializedAdditionalRawData) + { + PhoneNumber = phoneNumber; + NetworkIdentifier = networkIdentifier; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SimSwapRetrievalContent() + { + } + + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + public string PhoneNumber { get; set; } + /// Network to query for this device. + public NetworkIdentifier NetworkIdentifier { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.Serialization.cs new file mode 100644 index 000000000000..51b89294c543 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class SimSwapRetrievalResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapRetrievalResult)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(Date)) + { + writer.WritePropertyName("date"u8); + writer.WriteStringValue(Date.Value, "O"); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SimSwapRetrievalResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapRetrievalResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSimSwapRetrievalResult(document.RootElement, options); + } + + internal static SimSwapRetrievalResult DeserializeSimSwapRetrievalResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + DateTimeOffset? date = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("date"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + date = property.Value.GetDateTimeOffset("O"); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SimSwapRetrievalResult(date, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SimSwapRetrievalResult)} does not support writing '{options.Format}' format."); + } + } + + SimSwapRetrievalResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapRetrievalResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SimSwapRetrievalResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SimSwapRetrievalResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapRetrievalResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.cs new file mode 100644 index 000000000000..696048ae6a51 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapRetrievalResult.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Response with SimSwap date. + public partial class SimSwapRetrievalResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + internal SimSwapRetrievalResult() + { + } + + /// Initializes a new instance of . + /// Datetime of most recent swap for SIM. + /// Keeps track of any properties unknown to the library. + internal SimSwapRetrievalResult(DateTimeOffset? date, IDictionary serializedAdditionalRawData) + { + Date = date; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Datetime of most recent swap for SIM. + public DateTimeOffset? Date { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.Serialization.cs new file mode 100644 index 000000000000..20fcdb2ae8c4 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.Serialization.cs @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class SimSwapVerificationContent : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapVerificationContent)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(PhoneNumber)) + { + writer.WritePropertyName("phoneNumber"u8); + writer.WriteStringValue(PhoneNumber); + } + if (Optional.IsDefined(MaxAgeHours)) + { + writer.WritePropertyName("maxAgeHours"u8); + writer.WriteNumberValue(MaxAgeHours.Value); + } + writer.WritePropertyName("networkIdentifier"u8); + writer.WriteObjectValue(NetworkIdentifier, options); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SimSwapVerificationContent IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapVerificationContent)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSimSwapVerificationContent(document.RootElement, options); + } + + internal static SimSwapVerificationContent DeserializeSimSwapVerificationContent(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + string phoneNumber = default; + int? maxAgeHours = default; + NetworkIdentifier networkIdentifier = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("phoneNumber"u8)) + { + phoneNumber = property.Value.GetString(); + continue; + } + if (property.NameEquals("maxAgeHours"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + maxAgeHours = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("networkIdentifier"u8)) + { + networkIdentifier = NetworkIdentifier.DeserializeNetworkIdentifier(property.Value, options); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SimSwapVerificationContent(phoneNumber, maxAgeHours, networkIdentifier, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SimSwapVerificationContent)} does not support writing '{options.Format}' format."); + } + } + + SimSwapVerificationContent IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapVerificationContent(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SimSwapVerificationContent)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SimSwapVerificationContent FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapVerificationContent(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.cs new file mode 100644 index 000000000000..d3bb25dee1c4 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationContent.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Request to verify SimSwap in period. + public partial class SimSwapVerificationContent + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// Identifier for the network to query for this device. + /// is null. + public SimSwapVerificationContent(NetworkIdentifier networkIdentifier) + { + Argument.AssertNotNull(networkIdentifier, nameof(networkIdentifier)); + + NetworkIdentifier = networkIdentifier; + } + + /// Initializes a new instance of . + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + /// Maximum lookback for SimSwap verification. + /// Identifier for the network to query for this device. + /// Keeps track of any properties unknown to the library. + internal SimSwapVerificationContent(string phoneNumber, int? maxAgeHours, NetworkIdentifier networkIdentifier, IDictionary serializedAdditionalRawData) + { + PhoneNumber = phoneNumber; + MaxAgeHours = maxAgeHours; + NetworkIdentifier = networkIdentifier; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SimSwapVerificationContent() + { + } + + /// Phone number in E.164 format (starting with country code), and optionally prefixed with '+'. + public string PhoneNumber { get; set; } + /// Maximum lookback for SimSwap verification. + public int? MaxAgeHours { get; set; } + /// Identifier for the network to query for this device. + public NetworkIdentifier NetworkIdentifier { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.Serialization.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.Serialization.cs new file mode 100644 index 000000000000..7b7ef5e173d7 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.Serialization.cs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.Communication.ProgrammableConnectivity +{ + public partial class SimSwapVerificationResult : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapVerificationResult)} does not support writing '{format}' format."); + } + + writer.WritePropertyName("verificationResult"u8); + writer.WriteBooleanValue(VerificationResult); + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + SimSwapVerificationResult IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(SimSwapVerificationResult)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeSimSwapVerificationResult(document.RootElement, options); + } + + internal static SimSwapVerificationResult DeserializeSimSwapVerificationResult(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool verificationResult = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("verificationResult"u8)) + { + verificationResult = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new SimSwapVerificationResult(verificationResult, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(SimSwapVerificationResult)} does not support writing '{options.Format}' format."); + } + } + + SimSwapVerificationResult IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapVerificationResult(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(SimSwapVerificationResult)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static SimSwapVerificationResult FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeSimSwapVerificationResult(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.cs new file mode 100644 index 000000000000..b10fbb9d29f4 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Generated/SimSwapVerificationResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.Communication.ProgrammableConnectivity +{ + /// Response verifying SimSwap in period. + public partial class SimSwapVerificationResult + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + /// True if the SIM has swapped in the specified period, False otherwise. + internal SimSwapVerificationResult(bool verificationResult) + { + VerificationResult = verificationResult; + } + + /// Initializes a new instance of . + /// True if the SIM has swapped in the specified period, False otherwise. + /// Keeps track of any properties unknown to the library. + internal SimSwapVerificationResult(bool verificationResult, IDictionary serializedAdditionalRawData) + { + VerificationResult = verificationResult; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Initializes a new instance of for deserialization. + internal SimSwapVerificationResult() + { + } + + /// True if the SIM has swapped in the specified period, False otherwise. + public bool VerificationResult { get; } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Properties/AssemblyInfo.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..98d4b07ed794 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/src/Properties/AssemblyInfo.cs @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Azure.Communication.ProgrammableConnectivity.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")] + +// Replace Microsoft.Test with the correct resource provider namepace for your service and uncomment. +// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/azure-services-resource-providers +// for the list of possible values. +[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.Template")] diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Azure.Communication.ProgrammableConnectivity.Tests.csproj b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Azure.Communication.ProgrammableConnectivity.Tests.csproj new file mode 100644 index 000000000000..4f7e5f50fc34 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Azure.Communication.ProgrammableConnectivity.Tests.csproj @@ -0,0 +1,20 @@ + + + $(RequiredTargetFrameworks) + + $(NoWarn);CS1591 + + + + + + + + + + + + + + + diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceLocation.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceLocation.cs new file mode 100644 index 000000000000..10b718cdbb22 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceLocation.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.ProgrammableConnectivity.Samples +{ + public partial class Samples_DeviceLocation + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeviceLocation_Verify_DeviceLocationVerify() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + latitude = 70, + longitude = -161, + accuracy = 91, + device = new + { + networkAccessIdentifier = "122345@domain.com", + phoneNumber = "+447000000000", + ipv4Address = new + { + ipv4 = "12.12.12.12", + port = 2442, + }, + ipv6Address = new + { + ipv6 = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", + port = 1643, + }, + }, + }); + Response response = client.Verify("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("verificationResult").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeviceLocation_Verify_DeviceLocationVerify_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + latitude = 70, + longitude = -161, + accuracy = 91, + device = new + { + networkAccessIdentifier = "122345@domain.com", + phoneNumber = "+447000000000", + ipv4Address = new + { + ipv4 = "12.12.12.12", + port = 2442, + }, + ipv6Address = new + { + ipv6 = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", + port = 1643, + }, + }, + }); + Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("verificationResult").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeviceLocation_Verify_DeviceLocationVerify_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + + DeviceLocationVerificationContent body = new DeviceLocationVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12"), 70, -161, 91, new LocationDevice + { + NetworkAccessIdentifier = "122345@domain.com", + PhoneNumber = "+447000000000", + Ipv4Address = new Ipv4Address("12.12.12.12", 2442), + Ipv6Address = new Ipv6Address("3001:0da8:75a3:0000:0000:8a2e:0370:7334", 1643), + }); + Response response = client.Verify("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeviceLocation_Verify_DeviceLocationVerify_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceLocation client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceLocationClient(apiVersion: "2024-02-09-preview"); + + DeviceLocationVerificationContent body = new DeviceLocationVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12"), 70, -161, 91, new LocationDevice + { + NetworkAccessIdentifier = "122345@domain.com", + PhoneNumber = "+447000000000", + Ipv4Address = new Ipv4Address("12.12.12.12", 2442), + Ipv6Address = new Ipv6Address("3001:0da8:75a3:0000:0000:8a2e:0370:7334", 1643), + }); + Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", body); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceNetwork.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceNetwork.cs new file mode 100644 index 000000000000..59af5885d825 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_DeviceNetwork.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.ProgrammableConnectivity.Samples +{ + public partial class Samples_DeviceNetwork + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeviceNetwork_Retrieve_DeviceNetworkRetrieve() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + identifierType = "ipv6", + identifier = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", + }); + Response response = client.Retrieve("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("networkCode").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeviceNetwork_Retrieve_DeviceNetworkRetrieve_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + identifierType = "ipv6", + identifier = "3001:0da8:75a3:0000:0000:8a2e:0370:7334", + }); + Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("networkCode").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_DeviceNetwork_Retrieve_DeviceNetworkRetrieve_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + + NetworkIdentifier body = new NetworkIdentifier("ipv6", "3001:0da8:75a3:0000:0000:8a2e:0370:7334"); + Response response = client.Retrieve("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_DeviceNetwork_Retrieve_DeviceNetworkRetrieve_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + DeviceNetwork client = new ProgrammableConnectivityClient(endpoint, credential).GetDeviceNetworkClient(apiVersion: "2024-02-09-preview"); + + NetworkIdentifier body = new NetworkIdentifier("ipv6", "3001:0da8:75a3:0000:0000:8a2e:0370:7334"); + Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", body); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_NumberVerification.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_NumberVerification.cs new file mode 100644 index 000000000000..2abed1066305 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_NumberVerification.cs @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.ProgrammableConnectivity.Samples +{ + public partial class Samples_NumberVerification + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberVerification_VerifyWithoutCode_NumberVerificationVerifyWithoutCode() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + phoneNumber = "+14424318793", + hashedPhoneNumber = "bwsl", + redirectUri = "https://www.contoso.com", + }); + Response response = client.VerifyWithoutCode("zdgrzzaxlodrvewbksn", content); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberVerification_VerifyWithoutCode_NumberVerificationVerifyWithoutCode_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + phoneNumber = "+14424318793", + hashedPhoneNumber = "bwsl", + redirectUri = "https://www.contoso.com", + }); + Response response = await client.VerifyWithoutCodeAsync("zdgrzzaxlodrvewbksn", content); + + Console.WriteLine(response.Status); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberVerification_VerifyWithoutCode_NumberVerificationVerifyWithoutCode_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + NumberVerificationWithoutCodeContent body = new NumberVerificationWithoutCodeContent(new NetworkIdentifier("ipv4", "12.12.12.12"), new Uri("https://www.contoso.com")) + { + PhoneNumber = "+14424318793", + HashedPhoneNumber = "bwsl", + }; + Response response = client.VerifyWithoutCode("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberVerification_VerifyWithoutCode_NumberVerificationVerifyWithoutCode_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + NumberVerificationWithoutCodeContent body = new NumberVerificationWithoutCodeContent(new NetworkIdentifier("ipv4", "12.12.12.12"), new Uri("https://www.contoso.com")) + { + PhoneNumber = "+14424318793", + HashedPhoneNumber = "bwsl", + }; + Response response = await client.VerifyWithoutCodeAsync("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberVerification_VerifyWithCode_NumberVerificationVerifyWithCode() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + apcCode = "yn", + }); + Response response = client.VerifyWithCode("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("verificationResult").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberVerification_VerifyWithCode_NumberVerificationVerifyWithCode_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + apcCode = "yn", + }); + Response response = await client.VerifyWithCodeAsync("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("verificationResult").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_NumberVerification_VerifyWithCode_NumberVerificationVerifyWithCode_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + NumberVerificationWithCodeContent body = new NumberVerificationWithCodeContent("yn"); + Response response = client.VerifyWithCode("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_NumberVerification_VerifyWithCode_NumberVerificationVerifyWithCode_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + NumberVerification client = new ProgrammableConnectivityClient(endpoint, credential).GetNumberVerificationClient(apiVersion: "2024-02-09-preview"); + + NumberVerificationWithCodeContent body = new NumberVerificationWithCodeContent("yn"); + Response response = await client.VerifyWithCodeAsync("zdgrzzaxlodrvewbksn", body); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_SimSwap.cs b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_SimSwap.cs new file mode 100644 index 000000000000..c0bbc0909db9 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tests/Generated/Samples/Samples_SimSwap.cs @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Text.Json; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using NUnit.Framework; + +namespace Azure.Communication.ProgrammableConnectivity.Samples +{ + public partial class Samples_SimSwap + { + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SimSwap_Retrieve_SimSwapRetrieve() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + phoneNumber = "+61215310263792", + networkIdentifier = new + { + identifierType = "IPv6", + identifier = "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + }, + }); + Response response = client.Retrieve("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SimSwap_Retrieve_SimSwapRetrieve_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + phoneNumber = "+61215310263792", + networkIdentifier = new + { + identifierType = "IPv6", + identifier = "2001:0db8:85a3:0000:0000:8a2e:0370:7334", + }, + }); + Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SimSwap_Retrieve_SimSwapRetrieve_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + SimSwapRetrievalContent body = new SimSwapRetrievalContent(new NetworkIdentifier("IPv6", "2001:0db8:85a3:0000:0000:8a2e:0370:7334")) + { + PhoneNumber = "+61215310263792", + }; + Response response = client.Retrieve("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SimSwap_Retrieve_SimSwapRetrieve_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + SimSwapRetrievalContent body = new SimSwapRetrievalContent(new NetworkIdentifier("IPv6", "2001:0db8:85a3:0000:0000:8a2e:0370:7334")) + { + PhoneNumber = "+61215310263792", + }; + Response response = await client.RetrieveAsync("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SimSwap_Verify_SimSwapVerify() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + maxAgeHours = 941, + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + }); + Response response = client.Verify("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("verificationResult").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SimSwap_Verify_SimSwapVerify_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + using RequestContent content = RequestContent.Create(new + { + maxAgeHours = 941, + networkIdentifier = new + { + identifierType = "ipv4", + identifier = "12.12.12.12", + }, + }); + Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", content); + + JsonElement result = JsonDocument.Parse(response.ContentStream).RootElement; + Console.WriteLine(result.GetProperty("verificationResult").ToString()); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public void Example_SimSwap_Verify_SimSwapVerify_Convenience() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + SimSwapVerificationContent body = new SimSwapVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12")) + { + MaxAgeHours = 941, + }; + Response response = client.Verify("zdgrzzaxlodrvewbksn", body); + } + + [Test] + [Ignore("Only validating compilation of examples")] + public async Task Example_SimSwap_Verify_SimSwapVerify_Convenience_Async() + { + Uri endpoint = new Uri(""); + TokenCredential credential = new DefaultAzureCredential(); + SimSwap client = new ProgrammableConnectivityClient(endpoint, credential).GetSimSwapClient(apiVersion: "2024-02-09-preview"); + + SimSwapVerificationContent body = new SimSwapVerificationContent(new NetworkIdentifier("ipv4", "12.12.12.12")) + { + MaxAgeHours = 941, + }; + Response response = await client.VerifyAsync("zdgrzzaxlodrvewbksn", body); + } + } +} diff --git a/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tsp-location.yaml b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tsp-location.yaml new file mode 100644 index 000000000000..56290f022cc6 --- /dev/null +++ b/sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/programmableconnectivity/Azure.ProgrammableConnectivity +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/programmableconnectivity/ci.yml b/sdk/programmableconnectivity/ci.yml new file mode 100644 index 000000000000..aeb7233b0c5f --- /dev/null +++ b/sdk/programmableconnectivity/ci.yml @@ -0,0 +1,35 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - main + - hotfix/* + - release/* + paths: + include: + - sdk/programmableconnectivity + - sdk/programmableconnectivity/ci.yml + - sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/programmableconnectivity + - sdk/programmableconnectivity/ci.yml + - sdk/programmableconnectivity/Azure.Communication.ProgrammableConnectivity + +extends: + template: /eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: programmableconnectivity + ArtifactName: packages + Artifacts: + - name: Azure.Communication.ProgrammableConnectivity + safeName: AzureCommunicationProgrammableConnectivity diff --git a/sdk/purview/Azure.Analytics.Purview.Account/src/autorest.md b/sdk/purview/Azure.Analytics.Purview.Account/src/autorest.md index 45ccf1bbc0bc..e96af4e879cc 100644 --- a/sdk/purview/Azure.Analytics.Purview.Account/src/autorest.md +++ b/sdk/purview/Azure.Analytics.Purview.Account/src/autorest.md @@ -4,7 +4,9 @@ Run `dotnet build /t:GenerateCode` to generate code. ```yaml title: PurviewAccount -input-file: https://github.com/Azure/azure-rest-api-specs/blob/b2bddfe2e59b5b14e559e0433b6e6d057bcff95d/specification/purview/data-plane/Azure.Analytics.Purview.Account/preview/2019-11-01-preview/account.json +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/purview/data-plane/readme.md + namespace: Azure.Analytics.Purview.Account security: AADToken security-scopes: https://purview.azure.net/.default @@ -57,3 +59,4 @@ directive: $.operationId = (mappingTable[$.operationId] ?? $.operationId); ``` + diff --git a/sdk/purview/Azure.Analytics.Purview.Administration/src/autorest.md b/sdk/purview/Azure.Analytics.Purview.Administration/src/autorest.md index 44b3da58b988..36b601a6cfe2 100644 --- a/sdk/purview/Azure.Analytics.Purview.Administration/src/autorest.md +++ b/sdk/purview/Azure.Analytics.Purview.Administration/src/autorest.md @@ -4,9 +4,8 @@ Run `dotnet build /t:GenerateCode` to generate code. ```yaml title: PurviewAdministration -input-file: - - https://github.com/Azure/azure-rest-api-specs/blob/0ebd4949e8e1cd9537ca5a07384c7661162cc7a6/specification/purview/data-plane/Azure.Analytics.Purview.Account/preview/2019-11-01-preview/account.json - - https://github.com/Azure/azure-rest-api-specs/blob/0ebd4949e8e1cd9537ca5a07384c7661162cc7a6/specification/purview/data-plane/Azure.Analytics.Purview.MetadataPolicies/preview/2021-07-01-preview/purviewMetadataPolicy.json +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/purview/data-plane/readme.md namespace: Azure.Analytics.Purview.Administration modelerfour: lenient-model-deduplication: true @@ -83,3 +82,4 @@ directive: $.operationId = "Purview" + $.operationId; } ``` + diff --git a/sdk/purview/Azure.Analytics.Purview.Catalog/src/autorest.md b/sdk/purview/Azure.Analytics.Purview.Catalog/src/autorest.md index 77f2f0c5b7da..75916e7bcf0a 100644 --- a/sdk/purview/Azure.Analytics.Purview.Catalog/src/autorest.md +++ b/sdk/purview/Azure.Analytics.Purview.Catalog/src/autorest.md @@ -4,9 +4,8 @@ Run `dotnet build /t:GenerateCode` to generate code. ```yaml title: PurviewCatalog -input-file: - -- https://github.com/Azure/azure-rest-api-specs/blob/ccbe894f6b012ca2000184307ed453fd68797b86/specification/purview/data-plane/Azure.Analytics.Purview.Catalog/preview/2022-03-01-preview/purviewcatalog.json +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/purview/data-plane/readme.md namespace: Azure.Analytics.Purview.Catalog @@ -81,3 +80,4 @@ directive: transform: > $.operationId = $.operationId.replace("_List", "_Get"); ``` + diff --git a/sdk/purview/Azure.Analytics.Purview.DataMap/src/Generated/Entity.cs b/sdk/purview/Azure.Analytics.Purview.DataMap/src/Generated/Entity.cs index 8edd445b2293..c64f94c26770 100644 --- a/sdk/purview/Azure.Analytics.Purview.DataMap/src/Generated/Entity.cs +++ b/sdk/purview/Azure.Analytics.Purview.DataMap/src/Generated/Entity.cs @@ -3616,7 +3616,7 @@ public virtual Response GetBusinessMetadataTemplate(RequestContext context) } /// Upload the file for creating Business Metadata in BULK. - /// Body parameter. + /// Multipart body. /// The cancellation token to use. /// is null. /// @@ -3631,7 +3631,7 @@ public virtual async Task> ImportBusinessMetadataAsyn } /// Upload the file for creating Business Metadata in BULK. - /// Body parameter. + /// Multipart body. /// The cancellation token to use. /// is null. /// diff --git a/sdk/purview/Azure.Analytics.Purview.DataMap/tsp-location.yaml b/sdk/purview/Azure.Analytics.Purview.DataMap/tsp-location.yaml index d4680673ecfc..4d8a42cbe34e 100644 --- a/sdk/purview/Azure.Analytics.Purview.DataMap/tsp-location.yaml +++ b/sdk/purview/Azure.Analytics.Purview.DataMap/tsp-location.yaml @@ -1,4 +1,4 @@ -repo: Azure/azure-rest-api-specs -commit: 6f5c5d483c9bd284d57862244163d7ff09a83491 -additionalDirectories: [] directory: specification/purview/Azure.Analytics.Purview.DataMap +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/purview/Azure.Analytics.Purview.Scanning/src/autorest.md b/sdk/purview/Azure.Analytics.Purview.Scanning/src/autorest.md index bed111da105c..e7c627cfaf15 100644 --- a/sdk/purview/Azure.Analytics.Purview.Scanning/src/autorest.md +++ b/sdk/purview/Azure.Analytics.Purview.Scanning/src/autorest.md @@ -4,7 +4,9 @@ Run `dotnet build /t:GenerateCode` to generate code. ```yaml title: PurviewScanningService -input-file: https://github.com/Azure/azure-rest-api-specs/blob/1c7df99f6a84335cfd7bf5be8c800d72c1dddbc2/specification/purview/data-plane/Azure.Analytics.Purview.Scanning/preview/2018-12-01-preview/scanningService.json +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/purview/data-plane/readme.md + namespace: Azure.Analytics.Purview.Scanning security: AADToken security-scopes: https://purview.azure.net/.default @@ -115,3 +117,4 @@ directive: $.operationId = (mappingTable[$.operationId] ?? $.operationId); ``` + diff --git a/sdk/purview/Azure.Analytics.Purview.Sharing/src/autorest.md b/sdk/purview/Azure.Analytics.Purview.Sharing/src/autorest.md index c34814b2486c..3b72af89f344 100644 --- a/sdk/purview/Azure.Analytics.Purview.Sharing/src/autorest.md +++ b/sdk/purview/Azure.Analytics.Purview.Sharing/src/autorest.md @@ -6,8 +6,8 @@ Run `dotnet build /t:GenerateCode` to generate code. > see https://aka.ms/autorest ``` yaml -input-file: -- https://github.com/Azure/azure-rest-api-specs/blob/40a953243ea428918de6e63758e853b7a24aa59a/specification/purview/data-plane/Azure.Analytics.Purview.Share/preview/2023-05-30-preview/share.json +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/purview/data-plane/readme.md namespace: Azure.Analytics.Purview.Sharing ``` @@ -60,3 +60,4 @@ directive: from: ShareResources_List to: ShareResources_GetAllShareResources ``` + diff --git a/sdk/purview/Azure.Analytics.Purview.Workflows/src/autorest.md b/sdk/purview/Azure.Analytics.Purview.Workflows/src/autorest.md index cde9e738e415..d8da73e6e629 100644 --- a/sdk/purview/Azure.Analytics.Purview.Workflows/src/autorest.md +++ b/sdk/purview/Azure.Analytics.Purview.Workflows/src/autorest.md @@ -6,8 +6,8 @@ Run `dotnet build /t:GenerateCode` to generate code. > see https://aka.ms/autorest ``` yaml -input-file: -- https://github.com/Azure/azure-rest-api-specs/blob/afa158ef56a05f6603924f4a493817cec332b113/specification/purview/data-plane/Azure.Analytics.Purview.Workflow/preview/2023-10-01-preview/purviewWorkflow.json +require: +- /mnt/vss/_work/1/s/azure-rest-api-specs/specification/purview/data-plane/readme.md security: AADToken security-scopes: https://purview.azure.net/.default @@ -20,3 +20,4 @@ security-scopes: https://purview.azure.net/.default + diff --git a/sdk/schemaregistry/Azure.Data.SchemaRegistry/tsp-location.yaml b/sdk/schemaregistry/Azure.Data.SchemaRegistry/tsp-location.yaml index d196f9d1e038..a4b124660048 100644 --- a/sdk/schemaregistry/Azure.Data.SchemaRegistry/tsp-location.yaml +++ b/sdk/schemaregistry/Azure.Data.SchemaRegistry/tsp-location.yaml @@ -1,4 +1,4 @@ -repo: Azure/azure-rest-api-specs directory: specification/schemaregistry/SchemaRegistry -additionalDirectories: [] -commit: 462574dbd02088c209bb1da3eef0d93f699e8de2 +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 +repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/storage/ci.yml b/sdk/storage/ci.yml index 2ca0501b60bd..4e749e6b85b1 100644 --- a/sdk/storage/ci.yml +++ b/sdk/storage/ci.yml @@ -12,6 +12,8 @@ trigger: - sdk/storage/Azure.Storage.DataMovement/ - sdk/storage/Azure.Storage.DataMovement.Blobs/ - sdk/storage/Azure.Storage.DataMovement.Files/ + exclude: + - sdk/storage/Azure.ResourceManager.Storage/ - sdk/storage/Azure.Storage.DataMovement.Blobs.Files.Shares/ exclude: - sdk/storage/Azure.ResourceManager.Storage/ diff --git a/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.net8.0.cs b/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.net8.0.cs index 98803e3c2771..79076102aaec 100644 --- a/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.net8.0.cs +++ b/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.net8.0.cs @@ -1,5 +1,16 @@ namespace Azure.AI.Translation.Document { + public partial class BatchOptions : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public BatchOptions() { } + public bool? TranslateTextWithinImage { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.AI.Translation.Document.BatchOptions System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.AI.Translation.Document.BatchOptions System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } public partial class DocumentFilterOrder { public DocumentFilterOrder(Azure.AI.Translation.Document.DocumentFilterProperty property, bool ascending = true) { } @@ -20,6 +31,8 @@ internal DocumentStatusResult() { } public System.DateTimeOffset LastModified { get { throw null; } } public System.Uri SourceDocumentUri { get { throw null; } } public Azure.AI.Translation.Document.DocumentTranslationStatus Status { get { throw null; } } + public int? TotalImageScansFailed { get { throw null; } } + public int? TotalImageScansSucceeded { get { throw null; } } public System.Uri TranslatedDocumentUri { get { throw null; } } public string TranslatedToLanguageCode { get { throw null; } } public float TranslationProgressPercentage { get { throw null; } } @@ -115,11 +128,12 @@ public DocumentTranslationClient(System.Uri endpoint, Azure.Core.TokenCredential } public partial class DocumentTranslationClientOptions : Azure.Core.ClientOptions { - public DocumentTranslationClientOptions(Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion version = Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion.V2024_05_01) { } + public DocumentTranslationClientOptions(Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion version = Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion.V2024_11_01_Preview) { } public Azure.AI.Translation.Document.DocumentTranslationAudience? Audience { get { throw null; } set { } } public enum ServiceVersion { V2024_05_01 = 1, + V2024_11_01_Preview = 2, } } public partial class DocumentTranslationFileFormat : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel @@ -275,10 +289,10 @@ public SingleDocumentTranslationClient(System.Uri endpoint, Azure.AzureKeyCreden public SingleDocumentTranslationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } public SingleDocumentTranslationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.AI.Translation.Document.DocumentTranslationClientOptions options) { } public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } - public virtual Azure.Response Translate(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } - public virtual Azure.Response Translate(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), Azure.RequestContext context = null) { throw null; } - public virtual System.Threading.Tasks.Task> TranslateAsync(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } - public virtual System.Threading.Tasks.Task TranslateAsync(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response Translate(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Translate(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> TranslateAsync(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task TranslateAsync(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), Azure.RequestContext context = null) { throw null; } } public enum StorageInputUriKind { @@ -300,6 +314,7 @@ public partial class TranslationBatch : System.ClientModel.Primitives.IJsonModel { public TranslationBatch(System.Collections.Generic.IEnumerable inputs) { } public System.Collections.Generic.IList Inputs { get { throw null; } } + public Azure.AI.Translation.Document.BatchOptions Options { get { throw null; } set { } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Document.TranslationBatch System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } diff --git a/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.netstandard2.0.cs b/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.netstandard2.0.cs index 98803e3c2771..79076102aaec 100644 --- a/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.netstandard2.0.cs +++ b/sdk/translation/Azure.AI.Translation.Document/api/Azure.AI.Translation.Document.netstandard2.0.cs @@ -1,5 +1,16 @@ namespace Azure.AI.Translation.Document { + public partial class BatchOptions : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel + { + public BatchOptions() { } + public bool? TranslateTextWithinImage { get { throw null; } set { } } + protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.AI.Translation.Document.BatchOptions System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } + Azure.AI.Translation.Document.BatchOptions System.ClientModel.Primitives.IPersistableModel.Create(System.BinaryData data, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + string System.ClientModel.Primitives.IPersistableModel.GetFormatFromOptions(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + System.BinaryData System.ClientModel.Primitives.IPersistableModel.Write(System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } + } public partial class DocumentFilterOrder { public DocumentFilterOrder(Azure.AI.Translation.Document.DocumentFilterProperty property, bool ascending = true) { } @@ -20,6 +31,8 @@ internal DocumentStatusResult() { } public System.DateTimeOffset LastModified { get { throw null; } } public System.Uri SourceDocumentUri { get { throw null; } } public Azure.AI.Translation.Document.DocumentTranslationStatus Status { get { throw null; } } + public int? TotalImageScansFailed { get { throw null; } } + public int? TotalImageScansSucceeded { get { throw null; } } public System.Uri TranslatedDocumentUri { get { throw null; } } public string TranslatedToLanguageCode { get { throw null; } } public float TranslationProgressPercentage { get { throw null; } } @@ -115,11 +128,12 @@ public DocumentTranslationClient(System.Uri endpoint, Azure.Core.TokenCredential } public partial class DocumentTranslationClientOptions : Azure.Core.ClientOptions { - public DocumentTranslationClientOptions(Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion version = Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion.V2024_05_01) { } + public DocumentTranslationClientOptions(Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion version = Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion.V2024_11_01_Preview) { } public Azure.AI.Translation.Document.DocumentTranslationAudience? Audience { get { throw null; } set { } } public enum ServiceVersion { V2024_05_01 = 1, + V2024_11_01_Preview = 2, } } public partial class DocumentTranslationFileFormat : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel @@ -275,10 +289,10 @@ public SingleDocumentTranslationClient(System.Uri endpoint, Azure.AzureKeyCreden public SingleDocumentTranslationClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { } public SingleDocumentTranslationClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.AI.Translation.Document.DocumentTranslationClientOptions options) { } public virtual Azure.Core.Pipeline.HttpPipeline Pipeline { get { throw null; } } - public virtual Azure.Response Translate(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } - public virtual Azure.Response Translate(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), Azure.RequestContext context = null) { throw null; } - public virtual System.Threading.Tasks.Task> TranslateAsync(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } - public virtual System.Threading.Tasks.Task TranslateAsync(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), Azure.RequestContext context = null) { throw null; } + public virtual Azure.Response Translate(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual Azure.Response Translate(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), Azure.RequestContext context = null) { throw null; } + public virtual System.Threading.Tasks.Task> TranslateAsync(string targetLanguage, Azure.AI.Translation.Document.DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } + public virtual System.Threading.Tasks.Task TranslateAsync(string targetLanguage, Azure.Core.RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = default(bool?), bool? translateTextWithinImage = default(bool?), Azure.RequestContext context = null) { throw null; } } public enum StorageInputUriKind { @@ -300,6 +314,7 @@ public partial class TranslationBatch : System.ClientModel.Primitives.IJsonModel { public TranslationBatch(System.Collections.Generic.IEnumerable inputs) { } public System.Collections.Generic.IList Inputs { get { throw null; } } + public Azure.AI.Translation.Document.BatchOptions Options { get { throw null; } set { } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Document.TranslationBatch System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.Serialization.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.Serialization.cs new file mode 100644 index 000000000000..fde85d4af4c4 --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.Serialization.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.ClientModel.Primitives; +using System.Collections.Generic; +using System.Text.Json; +using Azure.Core; + +namespace Azure.AI.Translation.Document +{ + public partial class BatchOptions : IUtf8JsonSerializable, IJsonModel + { + void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) => ((IJsonModel)this).Write(writer, ModelSerializationExtensions.WireOptions); + + void IJsonModel.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + writer.WriteStartObject(); + JsonModelWriteCore(writer, options); + writer.WriteEndObject(); + } + + /// The JSON writer. + /// The client options for reading and writing models. + protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchOptions)} does not support writing '{format}' format."); + } + + if (Optional.IsDefined(TranslateTextWithinImage)) + { + writer.WritePropertyName("translateTextWithinImage"u8); + writer.WriteBooleanValue(TranslateTextWithinImage.Value); + } + if (options.Format != "W" && _serializedAdditionalRawData != null) + { + foreach (var item in _serializedAdditionalRawData) + { + writer.WritePropertyName(item.Key); +#if NET6_0_OR_GREATER + writer.WriteRawValue(item.Value); +#else + using (JsonDocument document = JsonDocument.Parse(item.Value, ModelSerializationExtensions.JsonDocumentOptions)) + { + JsonSerializer.Serialize(writer, document.RootElement); + } +#endif + } + } + } + + BatchOptions IJsonModel.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + if (format != "J") + { + throw new FormatException($"The model {nameof(BatchOptions)} does not support reading '{format}' format."); + } + + using JsonDocument document = JsonDocument.ParseValue(ref reader); + return DeserializeBatchOptions(document.RootElement, options); + } + + internal static BatchOptions DeserializeBatchOptions(JsonElement element, ModelReaderWriterOptions options = null) + { + options ??= ModelSerializationExtensions.WireOptions; + + if (element.ValueKind == JsonValueKind.Null) + { + return null; + } + bool? translateTextWithinImage = default; + IDictionary serializedAdditionalRawData = default; + Dictionary rawDataDictionary = new Dictionary(); + foreach (var property in element.EnumerateObject()) + { + if (property.NameEquals("translateTextWithinImage"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + translateTextWithinImage = property.Value.GetBoolean(); + continue; + } + if (options.Format != "W") + { + rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); + } + } + serializedAdditionalRawData = rawDataDictionary; + return new BatchOptions(translateTextWithinImage, serializedAdditionalRawData); + } + + BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + return ModelReaderWriter.Write(this, options); + default: + throw new FormatException($"The model {nameof(BatchOptions)} does not support writing '{options.Format}' format."); + } + } + + BatchOptions IPersistableModel.Create(BinaryData data, ModelReaderWriterOptions options) + { + var format = options.Format == "W" ? ((IPersistableModel)this).GetFormatFromOptions(options) : options.Format; + + switch (format) + { + case "J": + { + using JsonDocument document = JsonDocument.Parse(data, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchOptions(document.RootElement, options); + } + default: + throw new FormatException($"The model {nameof(BatchOptions)} does not support reading '{options.Format}' format."); + } + } + + string IPersistableModel.GetFormatFromOptions(ModelReaderWriterOptions options) => "J"; + + /// Deserializes the model from a raw response. + /// The response to deserialize the model from. + internal static BatchOptions FromResponse(Response response) + { + using var document = JsonDocument.Parse(response.Content, ModelSerializationExtensions.JsonDocumentOptions); + return DeserializeBatchOptions(document.RootElement); + } + + /// Convert into a . + internal virtual RequestContent ToRequestContent() + { + var content = new Utf8JsonRequestContent(); + content.JsonWriter.WriteObjectValue(this, ModelSerializationExtensions.WireOptions); + return content; + } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.cs new file mode 100644 index 000000000000..8ddbbf8d7ceb --- /dev/null +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchOptions.cs @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// + +#nullable disable + +using System; +using System.Collections.Generic; + +namespace Azure.AI.Translation.Document +{ + /// Translation batch request options. + public partial class BatchOptions + { + /// + /// Keeps track of any properties unknown to the library. + /// + /// To assign an object to the value of this property use . + /// + /// + /// To assign an already formatted json string to this property use . + /// + /// + /// Examples: + /// + /// + /// BinaryData.FromObjectAsJson("foo") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromString("\"foo\"") + /// Creates a payload of "foo". + /// + /// + /// BinaryData.FromObjectAsJson(new { key = "value" }) + /// Creates a payload of { "key": "value" }. + /// + /// + /// BinaryData.FromString("{\"key\": \"value\"}") + /// Creates a payload of { "key": "value" }. + /// + /// + /// + /// + private IDictionary _serializedAdditionalRawData; + + /// Initializes a new instance of . + public BatchOptions() + { + } + + /// Initializes a new instance of . + /// Translation text within an image option. + /// Keeps track of any properties unknown to the library. + internal BatchOptions(bool? translateTextWithinImage, IDictionary serializedAdditionalRawData) + { + TranslateTextWithinImage = translateTextWithinImage; + _serializedAdditionalRawData = serializedAdditionalRawData; + } + + /// Translation text within an image option. + public bool? TranslateTextWithinImage { get; set; } + } +} diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.Serialization.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.Serialization.cs index 91a67c9705b9..dac005426f30 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.Serialization.cs @@ -60,6 +60,16 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteStringValue(Id); writer.WritePropertyName("characterCharged"u8); writer.WriteNumberValue(CharactersCharged); + if (Optional.IsDefined(TotalImageScansSucceeded)) + { + writer.WritePropertyName("totalImageScansSucceeded"u8); + writer.WriteNumberValue(TotalImageScansSucceeded.Value); + } + if (Optional.IsDefined(TotalImageScansFailed)) + { + writer.WritePropertyName("totalImageScansFailed"u8); + writer.WriteNumberValue(TotalImageScansFailed.Value); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -107,6 +117,8 @@ internal static DocumentStatusResult DeserializeDocumentStatusResult(JsonElement float progress = default; string id = default; long characterCharged = default; + int? totalImageScansSucceeded = default; + int? totalImageScansFailed = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -169,6 +181,24 @@ internal static DocumentStatusResult DeserializeDocumentStatusResult(JsonElement characterCharged = property.Value.GetInt64(); continue; } + if (property.NameEquals("totalImageScansSucceeded"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + totalImageScansSucceeded = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("totalImageScansFailed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + totalImageScansFailed = property.Value.GetInt32(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); @@ -186,6 +216,8 @@ internal static DocumentStatusResult DeserializeDocumentStatusResult(JsonElement progress, id, characterCharged, + totalImageScansSucceeded, + totalImageScansFailed, serializedAdditionalRawData); } diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.cs index ad2734f53e62..70297a750585 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentStatusResult.cs @@ -84,8 +84,10 @@ internal DocumentStatusResult(Uri sourceDocumentUri, DateTimeOffset createdOn, D /// Progress of the translation if available. /// Document Id. /// Character charged by the API. + /// Total image scans charged by the API. + /// Total image scans failed. /// Keeps track of any properties unknown to the library. - internal DocumentStatusResult(Uri translatedDocumentUri, Uri sourceDocumentUri, DateTimeOffset createdOn, DateTimeOffset lastModified, DocumentTranslationStatus status, string translatedToLanguageCode, JsonElement error, float progress, string id, long charactersCharged, IDictionary serializedAdditionalRawData) + internal DocumentStatusResult(Uri translatedDocumentUri, Uri sourceDocumentUri, DateTimeOffset createdOn, DateTimeOffset lastModified, DocumentTranslationStatus status, string translatedToLanguageCode, JsonElement error, float progress, string id, long charactersCharged, int? totalImageScansSucceeded, int? totalImageScansFailed, IDictionary serializedAdditionalRawData) { TranslatedDocumentUri = translatedDocumentUri; SourceDocumentUri = sourceDocumentUri; @@ -97,6 +99,8 @@ internal DocumentStatusResult(Uri translatedDocumentUri, Uri sourceDocumentUri, Progress = progress; Id = id; CharactersCharged = charactersCharged; + TotalImageScansSucceeded = totalImageScansSucceeded; + TotalImageScansFailed = totalImageScansFailed; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -104,5 +108,9 @@ internal DocumentStatusResult(Uri translatedDocumentUri, Uri sourceDocumentUri, internal DocumentStatusResult() { } + /// Total image scans charged by the API. + public int? TotalImageScansSucceeded { get; } + /// Total image scans failed. + public int? TotalImageScansFailed { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentTranslationClientOptions.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentTranslationClientOptions.cs index fc44e6926c9c..973affa55f5d 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentTranslationClientOptions.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/DocumentTranslationClientOptions.cs @@ -13,13 +13,15 @@ namespace Azure.AI.Translation.Document /// Client options for Azure.AI.Translation.Document library clients. public partial class DocumentTranslationClientOptions : ClientOptions { - private const ServiceVersion LatestVersion = ServiceVersion.V2024_05_01; + private const ServiceVersion LatestVersion = ServiceVersion.V2024_11_01_Preview; /// The version of the service to use. public enum ServiceVersion { /// Service version "2024-05-01". V2024_05_01 = 1, + /// Service version "2024-11-01-preview". + V2024_11_01_Preview = 2, } internal string Version { get; } diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/SingleDocumentTranslationClient.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/SingleDocumentTranslationClient.cs index 2f99db2b3d0d..25acf7194b2f 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/SingleDocumentTranslationClient.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/SingleDocumentTranslationClient.cs @@ -109,17 +109,18 @@ public SingleDocumentTranslationClient(Uri endpoint, TokenCredential credential, /// Specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. /// Possible values are: true (default) or false. /// + /// Optional boolean parameter to translate text within an image in the document. /// The cancellation token to use. /// or is null. /// Use this API to submit a single translation request to the Document Translation Service. - public virtual async Task> TranslateAsync(string targetLanguage, DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = null, CancellationToken cancellationToken = default) + public virtual async Task> TranslateAsync(string targetLanguage, DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = null, bool? translateTextWithinImage = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); Argument.AssertNotNull(documentTranslateContent, nameof(documentTranslateContent)); using MultipartFormDataRequestContent content = documentTranslateContent.ToMultipartRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = await TranslateAsync(targetLanguage, content, content.ContentType, sourceLanguage, category, allowFallback, context).ConfigureAwait(false); + Response response = await TranslateAsync(targetLanguage, content, content.ContentType, sourceLanguage, category, allowFallback, translateTextWithinImage, context).ConfigureAwait(false); return Response.FromValue(response.Content, response); } @@ -144,17 +145,18 @@ public virtual async Task> TranslateAsync(string targetLang /// Specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. /// Possible values are: true (default) or false. /// + /// Optional boolean parameter to translate text within an image in the document. /// The cancellation token to use. /// or is null. /// Use this API to submit a single translation request to the Document Translation Service. - public virtual Response Translate(string targetLanguage, DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = null, CancellationToken cancellationToken = default) + public virtual Response Translate(string targetLanguage, DocumentTranslateContent documentTranslateContent, string sourceLanguage = null, string category = null, bool? allowFallback = null, bool? translateTextWithinImage = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); Argument.AssertNotNull(documentTranslateContent, nameof(documentTranslateContent)); using MultipartFormDataRequestContent content = documentTranslateContent.ToMultipartRequestContent(); RequestContext context = FromCancellationToken(cancellationToken); - Response response = Translate(targetLanguage, content, content.ContentType, sourceLanguage, category, allowFallback, context); + Response response = Translate(targetLanguage, content, content.ContentType, sourceLanguage, category, allowFallback, translateTextWithinImage, context); return Response.FromValue(response.Content, response); } @@ -168,7 +170,7 @@ public virtual Response Translate(string targetLanguage, DocumentTra /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// @@ -194,11 +196,12 @@ public virtual Response Translate(string targetLanguage, DocumentTra /// Specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. /// Possible values are: true (default) or false. /// + /// Optional boolean parameter to translate text within an image in the document. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// or is null. /// Service returned a non-success status code. /// The response returned from the service. - public virtual async Task TranslateAsync(string targetLanguage, RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = null, RequestContext context = null) + public virtual async Task TranslateAsync(string targetLanguage, RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = null, bool? translateTextWithinImage = null, RequestContext context = null) { Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); Argument.AssertNotNull(content, nameof(content)); @@ -207,7 +210,7 @@ public virtual async Task TranslateAsync(string targetLanguage, Reques scope.Start(); try { - using HttpMessage message = CreateTranslateRequest(targetLanguage, content, contentType, sourceLanguage, category, allowFallback, context); + using HttpMessage message = CreateTranslateRequest(targetLanguage, content, contentType, sourceLanguage, category, allowFallback, translateTextWithinImage, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) @@ -227,7 +230,7 @@ public virtual async Task TranslateAsync(string targetLanguage, Reques /// /// /// - /// Please try the simpler convenience overload with strongly typed models first. + /// Please try the simpler convenience overload with strongly typed models first. /// /// /// @@ -253,11 +256,12 @@ public virtual async Task TranslateAsync(string targetLanguage, Reques /// Specifies that the service is allowed to fall back to a general system when a custom system doesn't exist. /// Possible values are: true (default) or false. /// + /// Optional boolean parameter to translate text within an image in the document. /// The request context, which can override default behaviors of the client pipeline on a per-call basis. /// or is null. /// Service returned a non-success status code. /// The response returned from the service. - public virtual Response Translate(string targetLanguage, RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = null, RequestContext context = null) + public virtual Response Translate(string targetLanguage, RequestContent content, string contentType, string sourceLanguage = null, string category = null, bool? allowFallback = null, bool? translateTextWithinImage = null, RequestContext context = null) { Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); Argument.AssertNotNull(content, nameof(content)); @@ -266,7 +270,7 @@ public virtual Response Translate(string targetLanguage, RequestContent content, scope.Start(); try { - using HttpMessage message = CreateTranslateRequest(targetLanguage, content, contentType, sourceLanguage, category, allowFallback, context); + using HttpMessage message = CreateTranslateRequest(targetLanguage, content, contentType, sourceLanguage, category, allowFallback, translateTextWithinImage, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) @@ -276,7 +280,7 @@ public virtual Response Translate(string targetLanguage, RequestContent content, } } - internal HttpMessage CreateTranslateRequest(string targetLanguage, RequestContent content, string contentType, string sourceLanguage, string category, bool? allowFallback, RequestContext context) + internal HttpMessage CreateTranslateRequest(string targetLanguage, RequestContent content, string contentType, string sourceLanguage, string category, bool? allowFallback, bool? translateTextWithinImage, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; @@ -299,6 +303,10 @@ internal HttpMessage CreateTranslateRequest(string targetLanguage, RequestConten { uri.AppendQuery("allowFallback", allowFallback.Value, true); } + if (translateTextWithinImage != null) + { + uri.AppendQuery("translateTextWithinImage", translateTextWithinImage.Value, true); + } request.Uri = uri; request.Headers.Add("Accept", "application/octet-stream"); request.Headers.Add("Content-Type", contentType); diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.Serialization.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.Serialization.cs index 2efa436c8043..b1d4343c8583 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.Serialization.cs @@ -41,6 +41,11 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteObjectValue(item, options); } writer.WriteEndArray(); + if (Optional.IsDefined(Options)) + { + writer.WritePropertyName("options"u8); + writer.WriteObjectValue(Options, options); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -79,6 +84,7 @@ internal static TranslationBatch DeserializeTranslationBatch(JsonElement element return null; } IList inputs = default; + BatchOptions options0 = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -93,13 +99,22 @@ internal static TranslationBatch DeserializeTranslationBatch(JsonElement element inputs = array; continue; } + if (property.NameEquals("options"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + options0 = BatchOptions.DeserializeBatchOptions(property.Value, options); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); } } serializedAdditionalRawData = rawDataDictionary; - return new TranslationBatch(inputs, serializedAdditionalRawData); + return new TranslationBatch(inputs, options0, serializedAdditionalRawData); } BinaryData IPersistableModel.Write(ModelReaderWriterOptions options) diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.cs index 82b309b8ec6a..5309362b29dc 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationBatch.cs @@ -58,10 +58,12 @@ public TranslationBatch(IEnumerable inputs) /// Initializes a new instance of . /// The input list of documents or folders containing documents. + /// The batch operation options. /// Keeps track of any properties unknown to the library. - internal TranslationBatch(IList inputs, IDictionary serializedAdditionalRawData) + internal TranslationBatch(IList inputs, BatchOptions options, IDictionary serializedAdditionalRawData) { Inputs = inputs; + Options = options; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -72,5 +74,7 @@ internal TranslationBatch() /// The input list of documents or folders containing documents. public IList Inputs { get; } + /// The batch operation options. + public BatchOptions Options { get; set; } } } diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.Serialization.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.Serialization.cs index 64617e14e8e1..f95268fde70f 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.Serialization.cs @@ -48,6 +48,16 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WriteNumberValue(Cancelled); writer.WritePropertyName("totalCharacterCharged"u8); writer.WriteNumberValue(TotalCharacterCharged); + if (Optional.IsDefined(TotalImageScansSucceeded)) + { + writer.WritePropertyName("totalImageScansSucceeded"u8); + writer.WriteNumberValue(TotalImageScansSucceeded.Value); + } + if (Optional.IsDefined(TotalImageScansFailed)) + { + writer.WritePropertyName("totalImageScansFailed"u8); + writer.WriteNumberValue(TotalImageScansFailed.Value); + } if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) @@ -92,6 +102,8 @@ internal static TranslationStatusSummary DeserializeTranslationStatusSummary(Jso int notYetStarted = default; int cancelled = default; long totalCharacterCharged = default; + int? totalImageScansSucceeded = default; + int? totalImageScansFailed = default; IDictionary serializedAdditionalRawData = default; Dictionary rawDataDictionary = new Dictionary(); foreach (var property in element.EnumerateObject()) @@ -131,6 +143,24 @@ internal static TranslationStatusSummary DeserializeTranslationStatusSummary(Jso totalCharacterCharged = property.Value.GetInt64(); continue; } + if (property.NameEquals("totalImageScansSucceeded"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + totalImageScansSucceeded = property.Value.GetInt32(); + continue; + } + if (property.NameEquals("totalImageScansFailed"u8)) + { + if (property.Value.ValueKind == JsonValueKind.Null) + { + continue; + } + totalImageScansFailed = property.Value.GetInt32(); + continue; + } if (options.Format != "W") { rawDataDictionary.Add(property.Name, BinaryData.FromString(property.Value.GetRawText())); @@ -145,6 +175,8 @@ internal static TranslationStatusSummary DeserializeTranslationStatusSummary(Jso notYetStarted, cancelled, totalCharacterCharged, + totalImageScansSucceeded, + totalImageScansFailed, serializedAdditionalRawData); } diff --git a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.cs b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.cs index 624bb2883520..b855d6e543b7 100644 --- a/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.cs +++ b/sdk/translation/Azure.AI.Translation.Document/src/Generated/TranslationStatusSummary.cs @@ -72,8 +72,10 @@ internal TranslationStatusSummary(int total, int failed, int success, int inProg /// Count of not yet started. /// Number of cancelled. /// Total characters charged by the API. + /// Total image scans charged by the API. + /// Total image scans failed. /// Keeps track of any properties unknown to the library. - internal TranslationStatusSummary(int total, int failed, int success, int inProgress, int notYetStarted, int cancelled, long totalCharacterCharged, IDictionary serializedAdditionalRawData) + internal TranslationStatusSummary(int total, int failed, int success, int inProgress, int notYetStarted, int cancelled, long totalCharacterCharged, int? totalImageScansSucceeded, int? totalImageScansFailed, IDictionary serializedAdditionalRawData) { Total = total; Failed = failed; @@ -82,6 +84,8 @@ internal TranslationStatusSummary(int total, int failed, int success, int inProg NotYetStarted = notYetStarted; Cancelled = cancelled; TotalCharacterCharged = totalCharacterCharged; + TotalImageScansSucceeded = totalImageScansSucceeded; + TotalImageScansFailed = totalImageScansFailed; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -104,5 +108,9 @@ internal TranslationStatusSummary() public int Cancelled { get; } /// Total characters charged by the API. public long TotalCharacterCharged { get; } + /// Total image scans charged by the API. + public int? TotalImageScansSucceeded { get; } + /// Total image scans failed. + public int? TotalImageScansFailed { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Document/tsp-location.yaml b/sdk/translation/Azure.AI.Translation.Document/tsp-location.yaml index 24ec8691077b..4a116cc36690 100644 --- a/sdk/translation/Azure.AI.Translation.Document/tsp-location.yaml +++ b/sdk/translation/Azure.AI.Translation.Document/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/translation/Azure.AI.DocumentTranslation -commit: a605f581cff367622d933b0c9a0eaffd106b1a7a +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs +additionalDirectories: diff --git a/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.net8.0.cs b/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.net8.0.cs index 3ac7ff4db781..fcab6d466834 100644 --- a/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.net8.0.cs +++ b/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.net8.0.cs @@ -2,24 +2,24 @@ namespace Azure.AI.Translation.Text { public static partial class AITranslationTextModelFactory { - public static Azure.AI.Translation.Text.BackTranslation BackTranslation(string normalizedText = null, string displayText = null, int examplesCount = 0, int frequencyCount = 0) { throw null; } - public static Azure.AI.Translation.Text.BreakSentenceItem BreakSentenceItem(Azure.AI.Translation.Text.DetectedLanguage detectedLanguage = null, System.Collections.Generic.IEnumerable sentencesLengths = null) { throw null; } - public static Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage(string language = null, float confidence = 0f) { throw null; } + public static Azure.AI.Translation.Text.BackTranslation BackTranslation(string normalizedText = null, string displayText = null, int numExamples = 0, int frequencyCount = 0) { throw null; } + public static Azure.AI.Translation.Text.BreakSentenceItem BreakSentenceItem(Azure.AI.Translation.Text.DetectedLanguage detectedLanguage = null, System.Collections.Generic.IEnumerable sentLen = null) { throw null; } + public static Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage(string language = null, float score = 0f) { throw null; } public static Azure.AI.Translation.Text.DictionaryExample DictionaryExample(string sourcePrefix = null, string sourceTerm = null, string sourceSuffix = null, string targetPrefix = null, string targetTerm = null, string targetSuffix = null) { throw null; } public static Azure.AI.Translation.Text.DictionaryExampleItem DictionaryExampleItem(string normalizedSource = null, string normalizedTarget = null, System.Collections.Generic.IEnumerable examples = null) { throw null; } public static Azure.AI.Translation.Text.DictionaryLookupItem DictionaryLookupItem(string normalizedSource = null, string displaySource = null, System.Collections.Generic.IEnumerable translations = null) { throw null; } public static Azure.AI.Translation.Text.DictionaryTranslation DictionaryTranslation(string normalizedTarget = null, string displayTarget = null, string posTag = null, float confidence = 0f, string prefixWord = null, System.Collections.Generic.IEnumerable backTranslations = null) { throw null; } public static Azure.AI.Translation.Text.GetSupportedLanguagesResult GetSupportedLanguagesResult(System.Collections.Generic.IReadOnlyDictionary translation = null, System.Collections.Generic.IReadOnlyDictionary transliteration = null, System.Collections.Generic.IReadOnlyDictionary dictionary = null) { throw null; } - public static Azure.AI.Translation.Text.LanguageScript LanguageScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } - public static Azure.AI.Translation.Text.SentenceBoundaries SentenceBoundaries(System.Collections.Generic.IEnumerable sourceSentencesLengths = null, System.Collections.Generic.IEnumerable translatedSentencesLengths = null) { throw null; } - public static Azure.AI.Translation.Text.SourceDictionaryLanguage SourceDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable translations = null) { throw null; } + public static Azure.AI.Translation.Text.LanguageScript LanguageScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } + public static Azure.AI.Translation.Text.SentenceBoundaries SentenceBoundaries(System.Collections.Generic.IEnumerable srcSentLen = null, System.Collections.Generic.IEnumerable transSentLen = null) { throw null; } + public static Azure.AI.Translation.Text.SourceDictionaryLanguage SourceDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable translations = null) { throw null; } public static Azure.AI.Translation.Text.SourceText SourceText(string text = null) { throw null; } - public static Azure.AI.Translation.Text.TargetDictionaryLanguage TargetDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, string code = null) { throw null; } - public static Azure.AI.Translation.Text.TranslatedTextAlignment TranslatedTextAlignment(string projections = null) { throw null; } + public static Azure.AI.Translation.Text.TargetDictionaryLanguage TargetDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, string code = null) { throw null; } + public static Azure.AI.Translation.Text.TranslatedTextAlignment TranslatedTextAlignment(string proj = null) { throw null; } public static Azure.AI.Translation.Text.TranslatedTextItem TranslatedTextItem(Azure.AI.Translation.Text.DetectedLanguage detectedLanguage = null, System.Collections.Generic.IEnumerable translations = null, Azure.AI.Translation.Text.SourceText sourceText = null) { throw null; } - public static Azure.AI.Translation.Text.TranslationLanguage TranslationLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } - public static Azure.AI.Translation.Text.TranslationText TranslationText(string targetLanguage = null, string text = null, Azure.AI.Translation.Text.TransliteratedText transliteration = null, Azure.AI.Translation.Text.TranslatedTextAlignment alignment = null, Azure.AI.Translation.Text.SentenceBoundaries sentenceBoundaries = null) { throw null; } - public static Azure.AI.Translation.Text.TransliterableScript TransliterableScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable targetLanguageScripts = null) { throw null; } + public static Azure.AI.Translation.Text.TranslationLanguage TranslationLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } + public static Azure.AI.Translation.Text.TranslationText TranslationText(string to = null, string text = null, Azure.AI.Translation.Text.TransliteratedText transliteration = null, Azure.AI.Translation.Text.TranslatedTextAlignment alignment = null, Azure.AI.Translation.Text.SentenceBoundaries sentLen = null) { throw null; } + public static Azure.AI.Translation.Text.TransliterableScript TransliterableScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable toScripts = null) { throw null; } public static Azure.AI.Translation.Text.TransliteratedText TransliteratedText(string text = null, string script = null) { throw null; } public static Azure.AI.Translation.Text.TransliterationLanguage TransliterationLanguage(string name = null, string nativeName = null, System.Collections.Generic.IEnumerable scripts = null) { throw null; } } @@ -27,9 +27,9 @@ public partial class BackTranslation : System.ClientModel.Primitives.IJsonModel< { internal BackTranslation() { } public string DisplayText { get { throw null; } } - public int ExamplesCount { get { throw null; } } public int FrequencyCount { get { throw null; } } public string NormalizedText { get { throw null; } } + public int NumExamples { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.BackTranslation System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -41,7 +41,7 @@ public partial class BreakSentenceItem : System.ClientModel.Primitives.IJsonMode { internal BreakSentenceItem() { } public Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage { get { throw null; } } - public System.Collections.Generic.IReadOnlyList SentencesLengths { get { throw null; } } + public System.Collections.Generic.IReadOnlyList SentLen { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.BreakSentenceItem System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -52,8 +52,8 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class DetectedLanguage : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal DetectedLanguage() { } - public float Confidence { get { throw null; } } public string Language { get { throw null; } } + public float Score { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.DetectedLanguage System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -169,7 +169,7 @@ public partial class LanguageScript : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal SentenceBoundaries() { } - public System.Collections.Generic.IReadOnlyList SourceSentencesLengths { get { throw null; } } - public System.Collections.Generic.IReadOnlyList TranslatedSentencesLengths { get { throw null; } } + public System.Collections.Generic.IReadOnlyList SrcSentLen { get { throw null; } } + public System.Collections.Generic.IReadOnlyList TransSentLen { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.SentenceBoundaries System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -205,7 +205,7 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class SourceDictionaryLanguage : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal SourceDictionaryLanguage() { } - public Azure.AI.Translation.Text.LanguageDirectionality Directionality { get { throw null; } } + public Azure.AI.Translation.Text.LanguageDirectionality Dir { get { throw null; } } public string Name { get { throw null; } } public string NativeName { get { throw null; } } public System.Collections.Generic.IReadOnlyList Translations { get { throw null; } } @@ -231,7 +231,7 @@ public partial class TargetDictionaryLanguage : System.ClientModel.Primitives.IJ { internal TargetDictionaryLanguage() { } public string Code { get { throw null; } } - public Azure.AI.Translation.Text.LanguageDirectionality Directionality { get { throw null; } } + public Azure.AI.Translation.Text.LanguageDirectionality Dir { get { throw null; } } public string Name { get { throw null; } } public string NativeName { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -343,7 +343,7 @@ public partial class TextTranslationTransliterateOptions public partial class TranslatedTextAlignment : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal TranslatedTextAlignment() { } - public string Projections { get { throw null; } } + public string Proj { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.TranslatedTextAlignment System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -367,7 +367,7 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class TranslationLanguage : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal TranslationLanguage() { } - public Azure.AI.Translation.Text.LanguageDirectionality Directionality { get { throw null; } } + public Azure.AI.Translation.Text.LanguageDirectionality Dir { get { throw null; } } public string Name { get { throw null; } } public string NativeName { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -381,9 +381,9 @@ public partial class TranslationText : System.ClientModel.Primitives.IJsonModel< { internal TranslationText() { } public Azure.AI.Translation.Text.TranslatedTextAlignment Alignment { get { throw null; } } - public Azure.AI.Translation.Text.SentenceBoundaries SentenceBoundaries { get { throw null; } } - public string TargetLanguage { get { throw null; } } + public Azure.AI.Translation.Text.SentenceBoundaries SentLen { get { throw null; } } public string Text { get { throw null; } } + public string To { get { throw null; } } public Azure.AI.Translation.Text.TransliteratedText Transliteration { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.TranslationText System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } @@ -395,7 +395,7 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class TransliterableScript : Azure.AI.Translation.Text.LanguageScript, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal TransliterableScript() { } - public System.Collections.Generic.IReadOnlyList TargetLanguageScripts { get { throw null; } } + public System.Collections.Generic.IReadOnlyList ToScripts { get { throw null; } } protected override void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.TransliterableScript System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } diff --git a/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs b/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs index 3ac7ff4db781..fcab6d466834 100644 --- a/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs +++ b/sdk/translation/Azure.AI.Translation.Text/api/Azure.AI.Translation.Text.netstandard2.0.cs @@ -2,24 +2,24 @@ namespace Azure.AI.Translation.Text { public static partial class AITranslationTextModelFactory { - public static Azure.AI.Translation.Text.BackTranslation BackTranslation(string normalizedText = null, string displayText = null, int examplesCount = 0, int frequencyCount = 0) { throw null; } - public static Azure.AI.Translation.Text.BreakSentenceItem BreakSentenceItem(Azure.AI.Translation.Text.DetectedLanguage detectedLanguage = null, System.Collections.Generic.IEnumerable sentencesLengths = null) { throw null; } - public static Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage(string language = null, float confidence = 0f) { throw null; } + public static Azure.AI.Translation.Text.BackTranslation BackTranslation(string normalizedText = null, string displayText = null, int numExamples = 0, int frequencyCount = 0) { throw null; } + public static Azure.AI.Translation.Text.BreakSentenceItem BreakSentenceItem(Azure.AI.Translation.Text.DetectedLanguage detectedLanguage = null, System.Collections.Generic.IEnumerable sentLen = null) { throw null; } + public static Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage(string language = null, float score = 0f) { throw null; } public static Azure.AI.Translation.Text.DictionaryExample DictionaryExample(string sourcePrefix = null, string sourceTerm = null, string sourceSuffix = null, string targetPrefix = null, string targetTerm = null, string targetSuffix = null) { throw null; } public static Azure.AI.Translation.Text.DictionaryExampleItem DictionaryExampleItem(string normalizedSource = null, string normalizedTarget = null, System.Collections.Generic.IEnumerable examples = null) { throw null; } public static Azure.AI.Translation.Text.DictionaryLookupItem DictionaryLookupItem(string normalizedSource = null, string displaySource = null, System.Collections.Generic.IEnumerable translations = null) { throw null; } public static Azure.AI.Translation.Text.DictionaryTranslation DictionaryTranslation(string normalizedTarget = null, string displayTarget = null, string posTag = null, float confidence = 0f, string prefixWord = null, System.Collections.Generic.IEnumerable backTranslations = null) { throw null; } public static Azure.AI.Translation.Text.GetSupportedLanguagesResult GetSupportedLanguagesResult(System.Collections.Generic.IReadOnlyDictionary translation = null, System.Collections.Generic.IReadOnlyDictionary transliteration = null, System.Collections.Generic.IReadOnlyDictionary dictionary = null) { throw null; } - public static Azure.AI.Translation.Text.LanguageScript LanguageScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } - public static Azure.AI.Translation.Text.SentenceBoundaries SentenceBoundaries(System.Collections.Generic.IEnumerable sourceSentencesLengths = null, System.Collections.Generic.IEnumerable translatedSentencesLengths = null) { throw null; } - public static Azure.AI.Translation.Text.SourceDictionaryLanguage SourceDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable translations = null) { throw null; } + public static Azure.AI.Translation.Text.LanguageScript LanguageScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } + public static Azure.AI.Translation.Text.SentenceBoundaries SentenceBoundaries(System.Collections.Generic.IEnumerable srcSentLen = null, System.Collections.Generic.IEnumerable transSentLen = null) { throw null; } + public static Azure.AI.Translation.Text.SourceDictionaryLanguage SourceDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable translations = null) { throw null; } public static Azure.AI.Translation.Text.SourceText SourceText(string text = null) { throw null; } - public static Azure.AI.Translation.Text.TargetDictionaryLanguage TargetDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, string code = null) { throw null; } - public static Azure.AI.Translation.Text.TranslatedTextAlignment TranslatedTextAlignment(string projections = null) { throw null; } + public static Azure.AI.Translation.Text.TargetDictionaryLanguage TargetDictionaryLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, string code = null) { throw null; } + public static Azure.AI.Translation.Text.TranslatedTextAlignment TranslatedTextAlignment(string proj = null) { throw null; } public static Azure.AI.Translation.Text.TranslatedTextItem TranslatedTextItem(Azure.AI.Translation.Text.DetectedLanguage detectedLanguage = null, System.Collections.Generic.IEnumerable translations = null, Azure.AI.Translation.Text.SourceText sourceText = null) { throw null; } - public static Azure.AI.Translation.Text.TranslationLanguage TranslationLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } - public static Azure.AI.Translation.Text.TranslationText TranslationText(string targetLanguage = null, string text = null, Azure.AI.Translation.Text.TransliteratedText transliteration = null, Azure.AI.Translation.Text.TranslatedTextAlignment alignment = null, Azure.AI.Translation.Text.SentenceBoundaries sentenceBoundaries = null) { throw null; } - public static Azure.AI.Translation.Text.TransliterableScript TransliterableScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality directionality = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable targetLanguageScripts = null) { throw null; } + public static Azure.AI.Translation.Text.TranslationLanguage TranslationLanguage(string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight) { throw null; } + public static Azure.AI.Translation.Text.TranslationText TranslationText(string to = null, string text = null, Azure.AI.Translation.Text.TransliteratedText transliteration = null, Azure.AI.Translation.Text.TranslatedTextAlignment alignment = null, Azure.AI.Translation.Text.SentenceBoundaries sentLen = null) { throw null; } + public static Azure.AI.Translation.Text.TransliterableScript TransliterableScript(string code = null, string name = null, string nativeName = null, Azure.AI.Translation.Text.LanguageDirectionality dir = Azure.AI.Translation.Text.LanguageDirectionality.LeftToRight, System.Collections.Generic.IEnumerable toScripts = null) { throw null; } public static Azure.AI.Translation.Text.TransliteratedText TransliteratedText(string text = null, string script = null) { throw null; } public static Azure.AI.Translation.Text.TransliterationLanguage TransliterationLanguage(string name = null, string nativeName = null, System.Collections.Generic.IEnumerable scripts = null) { throw null; } } @@ -27,9 +27,9 @@ public partial class BackTranslation : System.ClientModel.Primitives.IJsonModel< { internal BackTranslation() { } public string DisplayText { get { throw null; } } - public int ExamplesCount { get { throw null; } } public int FrequencyCount { get { throw null; } } public string NormalizedText { get { throw null; } } + public int NumExamples { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.BackTranslation System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -41,7 +41,7 @@ public partial class BreakSentenceItem : System.ClientModel.Primitives.IJsonMode { internal BreakSentenceItem() { } public Azure.AI.Translation.Text.DetectedLanguage DetectedLanguage { get { throw null; } } - public System.Collections.Generic.IReadOnlyList SentencesLengths { get { throw null; } } + public System.Collections.Generic.IReadOnlyList SentLen { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.BreakSentenceItem System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -52,8 +52,8 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class DetectedLanguage : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal DetectedLanguage() { } - public float Confidence { get { throw null; } } public string Language { get { throw null; } } + public float Score { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.DetectedLanguage System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -169,7 +169,7 @@ public partial class LanguageScript : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal SentenceBoundaries() { } - public System.Collections.Generic.IReadOnlyList SourceSentencesLengths { get { throw null; } } - public System.Collections.Generic.IReadOnlyList TranslatedSentencesLengths { get { throw null; } } + public System.Collections.Generic.IReadOnlyList SrcSentLen { get { throw null; } } + public System.Collections.Generic.IReadOnlyList TransSentLen { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.SentenceBoundaries System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -205,7 +205,7 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class SourceDictionaryLanguage : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal SourceDictionaryLanguage() { } - public Azure.AI.Translation.Text.LanguageDirectionality Directionality { get { throw null; } } + public Azure.AI.Translation.Text.LanguageDirectionality Dir { get { throw null; } } public string Name { get { throw null; } } public string NativeName { get { throw null; } } public System.Collections.Generic.IReadOnlyList Translations { get { throw null; } } @@ -231,7 +231,7 @@ public partial class TargetDictionaryLanguage : System.ClientModel.Primitives.IJ { internal TargetDictionaryLanguage() { } public string Code { get { throw null; } } - public Azure.AI.Translation.Text.LanguageDirectionality Directionality { get { throw null; } } + public Azure.AI.Translation.Text.LanguageDirectionality Dir { get { throw null; } } public string Name { get { throw null; } } public string NativeName { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -343,7 +343,7 @@ public partial class TextTranslationTransliterateOptions public partial class TranslatedTextAlignment : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal TranslatedTextAlignment() { } - public string Projections { get { throw null; } } + public string Proj { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.TranslatedTextAlignment System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -367,7 +367,7 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class TranslationLanguage : System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal TranslationLanguage() { } - public Azure.AI.Translation.Text.LanguageDirectionality Directionality { get { throw null; } } + public Azure.AI.Translation.Text.LanguageDirectionality Dir { get { throw null; } } public string Name { get { throw null; } } public string NativeName { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } @@ -381,9 +381,9 @@ public partial class TranslationText : System.ClientModel.Primitives.IJsonModel< { internal TranslationText() { } public Azure.AI.Translation.Text.TranslatedTextAlignment Alignment { get { throw null; } } - public Azure.AI.Translation.Text.SentenceBoundaries SentenceBoundaries { get { throw null; } } - public string TargetLanguage { get { throw null; } } + public Azure.AI.Translation.Text.SentenceBoundaries SentLen { get { throw null; } } public string Text { get { throw null; } } + public string To { get { throw null; } } public Azure.AI.Translation.Text.TransliteratedText Transliteration { get { throw null; } } protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.TranslationText System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } @@ -395,7 +395,7 @@ protected virtual void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer public partial class TransliterableScript : Azure.AI.Translation.Text.LanguageScript, System.ClientModel.Primitives.IJsonModel, System.ClientModel.Primitives.IPersistableModel { internal TransliterableScript() { } - public System.Collections.Generic.IReadOnlyList TargetLanguageScripts { get { throw null; } } + public System.Collections.Generic.IReadOnlyList ToScripts { get { throw null; } } protected override void JsonModelWriteCore(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } Azure.AI.Translation.Text.TransliterableScript System.ClientModel.Primitives.IJsonModel.Create(ref System.Text.Json.Utf8JsonReader reader, System.ClientModel.Primitives.ModelReaderWriterOptions options) { throw null; } void System.ClientModel.Primitives.IJsonModel.Write(System.Text.Json.Utf8JsonWriter writer, System.ClientModel.Primitives.ModelReaderWriterOptions options) { } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/AITranslationTextModelFactory.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/AITranslationTextModelFactory.cs index 2348b6d02f3d..7ecbf4b5c5d2 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/AITranslationTextModelFactory.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/AITranslationTextModelFactory.cs @@ -30,11 +30,11 @@ public static GetSupportedLanguagesResult GetSupportedLanguagesResult(IReadOnlyD /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// A new instance for mocking. - public static TranslationLanguage TranslationLanguage(string name = null, string nativeName = null, LanguageDirectionality directionality = default) + public static TranslationLanguage TranslationLanguage(string name = null, string nativeName = null, LanguageDirectionality dir = default) { - return new TranslationLanguage(name, nativeName, directionality, serializedAdditionalRawData: null); + return new TranslationLanguage(name, nativeName, dir, serializedAdditionalRawData: null); } /// Initializes a new instance of . @@ -53,55 +53,55 @@ public static TransliterationLanguage TransliterationLanguage(string name = null /// Code identifying the script. /// Display name of the script in the locale requested via Accept-Language header. /// Display name of the language in the locale native for the language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - /// List of scripts available to convert text to. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// List of scripts available to convert text to. /// A new instance for mocking. - public static TransliterableScript TransliterableScript(string code = null, string name = null, string nativeName = null, LanguageDirectionality directionality = default, IEnumerable targetLanguageScripts = null) + public static TransliterableScript TransliterableScript(string code = null, string name = null, string nativeName = null, LanguageDirectionality dir = default, IEnumerable toScripts = null) { - targetLanguageScripts ??= new List(); + toScripts ??= new List(); return new TransliterableScript( code, name, nativeName, - directionality, + dir, serializedAdditionalRawData: null, - targetLanguageScripts?.ToList()); + toScripts?.ToList()); } /// Initializes a new instance of . /// Code identifying the script. /// Display name of the script in the locale requested via Accept-Language header. /// Display name of the language in the locale native for the language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// A new instance for mocking. - public static LanguageScript LanguageScript(string code = null, string name = null, string nativeName = null, LanguageDirectionality directionality = default) + public static LanguageScript LanguageScript(string code = null, string name = null, string nativeName = null, LanguageDirectionality dir = default) { - return new LanguageScript(code, name, nativeName, directionality, serializedAdditionalRawData: null); + return new LanguageScript(code, name, nativeName, dir, serializedAdditionalRawData: null); } /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// List of languages with alterative translations and examples for the query expressed in the source language. /// A new instance for mocking. - public static SourceDictionaryLanguage SourceDictionaryLanguage(string name = null, string nativeName = null, LanguageDirectionality directionality = default, IEnumerable translations = null) + public static SourceDictionaryLanguage SourceDictionaryLanguage(string name = null, string nativeName = null, LanguageDirectionality dir = default, IEnumerable translations = null) { translations ??= new List(); - return new SourceDictionaryLanguage(name, nativeName, directionality, translations?.ToList(), serializedAdditionalRawData: null); + return new SourceDictionaryLanguage(name, nativeName, dir, translations?.ToList(), serializedAdditionalRawData: null); } /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// Language code identifying the target language. /// A new instance for mocking. - public static TargetDictionaryLanguage TargetDictionaryLanguage(string name = null, string nativeName = null, LanguageDirectionality directionality = default, string code = null) + public static TargetDictionaryLanguage TargetDictionaryLanguage(string name = null, string nativeName = null, LanguageDirectionality dir = default, string code = null) { - return new TargetDictionaryLanguage(name, nativeName, directionality, code, serializedAdditionalRawData: null); + return new TargetDictionaryLanguage(name, nativeName, dir, code, serializedAdditionalRawData: null); } /// Initializes a new instance of . @@ -126,31 +126,31 @@ public static TranslatedTextItem TranslatedTextItem(DetectedLanguage detectedLan /// Initializes a new instance of . /// A string representing the code of the detected language. - /// + /// /// A float value indicating the confidence in the result. /// The score is between zero and one and a low score indicates a low confidence. /// /// A new instance for mocking. - public static DetectedLanguage DetectedLanguage(string language = null, float confidence = default) + public static DetectedLanguage DetectedLanguage(string language = null, float score = default) { - return new DetectedLanguage(language, confidence, serializedAdditionalRawData: null); + return new DetectedLanguage(language, score, serializedAdditionalRawData: null); } /// Initializes a new instance of . - /// A string representing the language code of the target language. + /// A string representing the language code of the target language. /// A string giving the translated text. /// An object giving the translated text in the script specified by the toScript parameter. /// Alignment information. - /// Sentence boundaries in the input and output texts. + /// Sentence boundaries in the input and output texts. /// A new instance for mocking. - public static TranslationText TranslationText(string targetLanguage = null, string text = null, TransliteratedText transliteration = null, TranslatedTextAlignment alignment = null, SentenceBoundaries sentenceBoundaries = null) + public static TranslationText TranslationText(string to = null, string text = null, TransliteratedText transliteration = null, TranslatedTextAlignment alignment = null, SentenceBoundaries sentLen = null) { return new TranslationText( - targetLanguage, + to, text, transliteration, alignment, - sentenceBoundaries, + sentLen, serializedAdditionalRawData: null); } @@ -164,7 +164,7 @@ public static TransliteratedText TransliteratedText(string text = null, string s } /// Initializes a new instance of . - /// + /// /// Maps input text to translated text. The alignment information is only provided when the request /// parameter includeAlignment is true. Alignment is returned as a string value of the following /// format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. @@ -173,27 +173,27 @@ public static TransliteratedText TransliteratedText(string text = null, string s /// be non-contiguous. When no alignment information is available, the alignment element will be empty. /// /// A new instance for mocking. - public static TranslatedTextAlignment TranslatedTextAlignment(string projections = null) + public static TranslatedTextAlignment TranslatedTextAlignment(string proj = null) { - return new TranslatedTextAlignment(projections, serializedAdditionalRawData: null); + return new TranslatedTextAlignment(proj, serializedAdditionalRawData: null); } /// Initializes a new instance of . - /// + /// /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - /// + /// /// An integer array representing the lengths of the sentences in the translated text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// /// A new instance for mocking. - public static SentenceBoundaries SentenceBoundaries(IEnumerable sourceSentencesLengths = null, IEnumerable translatedSentencesLengths = null) + public static SentenceBoundaries SentenceBoundaries(IEnumerable srcSentLen = null, IEnumerable transSentLen = null) { - sourceSentencesLengths ??= new List(); - translatedSentencesLengths ??= new List(); + srcSentLen ??= new List(); + transSentLen ??= new List(); - return new SentenceBoundaries(sourceSentencesLengths?.ToList(), translatedSentencesLengths?.ToList(), serializedAdditionalRawData: null); + return new SentenceBoundaries(srcSentLen?.ToList(), transSentLen?.ToList(), serializedAdditionalRawData: null); } /// Initializes a new instance of . @@ -206,16 +206,16 @@ public static SourceText SourceText(string text = null) /// Initializes a new instance of . /// The detectedLanguage property is only present in the result object when language auto-detection is requested. - /// + /// /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// /// A new instance for mocking. - public static BreakSentenceItem BreakSentenceItem(DetectedLanguage detectedLanguage = null, IEnumerable sentencesLengths = null) + public static BreakSentenceItem BreakSentenceItem(DetectedLanguage detectedLanguage = null, IEnumerable sentLen = null) { - sentencesLengths ??= new List(); + sentLen ??= new List(); - return new BreakSentenceItem(detectedLanguage, sentencesLengths?.ToList(), serializedAdditionalRawData: null); + return new BreakSentenceItem(detectedLanguage, sentLen?.ToList(), serializedAdditionalRawData: null); } /// Initializes a new instance of . @@ -292,7 +292,7 @@ public static DictionaryTranslation DictionaryTranslation(string normalizedTarge /// A string giving the source term that is a back-translation of the target in a form best /// suited for end-user display. /// - /// + /// /// An integer representing the number of examples that are available for this translation pair. /// Actual examples must be retrieved with a separate call to lookup examples. The number is mostly /// intended to facilitate display in a UX. For example, a user interface may add a hyperlink @@ -306,9 +306,9 @@ public static DictionaryTranslation DictionaryTranslation(string normalizedTarge /// field is to provide a user interface with a means to sort back-translations so the most frequent terms are first. /// /// A new instance for mocking. - public static BackTranslation BackTranslation(string normalizedText = null, string displayText = null, int examplesCount = default, int frequencyCount = default) + public static BackTranslation BackTranslation(string normalizedText = null, string displayText = null, int numExamples = default, int frequencyCount = default) { - return new BackTranslation(normalizedText, displayText, examplesCount, frequencyCount, serializedAdditionalRawData: null); + return new BackTranslation(normalizedText, displayText, numExamples, frequencyCount, serializedAdditionalRawData: null); } /// Initializes a new instance of . diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.Serialization.cs index 0ae7b65f4b68..07bfeb3086ed 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.Serialization.cs @@ -39,7 +39,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("displayText"u8); writer.WriteStringValue(DisplayText); writer.WritePropertyName("numExamples"u8); - writer.WriteNumberValue(ExamplesCount); + writer.WriteNumberValue(NumExamples); writer.WritePropertyName("frequencyCount"u8); writer.WriteNumberValue(FrequencyCount); if (options.Format != "W" && _serializedAdditionalRawData != null) diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.cs index 5eeb74c3c083..9e30c50706fe 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BackTranslation.cs @@ -54,7 +54,7 @@ public partial class BackTranslation /// A string giving the source term that is a back-translation of the target in a form best /// suited for end-user display. /// - /// + /// /// An integer representing the number of examples that are available for this translation pair. /// Actual examples must be retrieved with a separate call to lookup examples. The number is mostly /// intended to facilitate display in a UX. For example, a user interface may add a hyperlink @@ -68,14 +68,14 @@ public partial class BackTranslation /// field is to provide a user interface with a means to sort back-translations so the most frequent terms are first. /// /// or is null. - internal BackTranslation(string normalizedText, string displayText, int examplesCount, int frequencyCount) + internal BackTranslation(string normalizedText, string displayText, int numExamples, int frequencyCount) { Argument.AssertNotNull(normalizedText, nameof(normalizedText)); Argument.AssertNotNull(displayText, nameof(displayText)); NormalizedText = normalizedText; DisplayText = displayText; - ExamplesCount = examplesCount; + NumExamples = numExamples; FrequencyCount = frequencyCount; } @@ -88,7 +88,7 @@ internal BackTranslation(string normalizedText, string displayText, int examples /// A string giving the source term that is a back-translation of the target in a form best /// suited for end-user display. /// - /// + /// /// An integer representing the number of examples that are available for this translation pair. /// Actual examples must be retrieved with a separate call to lookup examples. The number is mostly /// intended to facilitate display in a UX. For example, a user interface may add a hyperlink @@ -102,11 +102,11 @@ internal BackTranslation(string normalizedText, string displayText, int examples /// field is to provide a user interface with a means to sort back-translations so the most frequent terms are first. /// /// Keeps track of any properties unknown to the library. - internal BackTranslation(string normalizedText, string displayText, int examplesCount, int frequencyCount, IDictionary serializedAdditionalRawData) + internal BackTranslation(string normalizedText, string displayText, int numExamples, int frequencyCount, IDictionary serializedAdditionalRawData) { NormalizedText = normalizedText; DisplayText = displayText; - ExamplesCount = examplesCount; + NumExamples = numExamples; FrequencyCount = frequencyCount; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -135,7 +135,7 @@ internal BackTranslation() /// by a call to lookup examples may be less than numExamples, because additional filtering may be /// applied on the fly to remove "bad" examples. /// - public int ExamplesCount { get; } + public int NumExamples { get; } /// /// An integer representing the frequency of this translation pair in the data. The main purpose of this /// field is to provide a user interface with a means to sort back-translations so the most frequent terms are first. diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.Serialization.cs index d81cd40955d0..3a7145034794 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.Serialization.cs @@ -41,7 +41,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName("sentLen"u8); writer.WriteStartArray(); - foreach (var item in SentencesLengths) + foreach (var item in SentLen) { writer.WriteNumberValue(item); } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.cs index c1d283a64f86..47a9734eb2e1 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/BreakSentenceItem.cs @@ -47,29 +47,29 @@ public partial class BreakSentenceItem private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// + /// /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - /// is null. - internal BreakSentenceItem(IEnumerable sentencesLengths) + /// is null. + internal BreakSentenceItem(IEnumerable sentLen) { - Argument.AssertNotNull(sentencesLengths, nameof(sentencesLengths)); + Argument.AssertNotNull(sentLen, nameof(sentLen)); - SentencesLengths = sentencesLengths.ToList(); + SentLen = sentLen.ToList(); } /// Initializes a new instance of . /// The detectedLanguage property is only present in the result object when language auto-detection is requested. - /// + /// /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// /// Keeps track of any properties unknown to the library. - internal BreakSentenceItem(DetectedLanguage detectedLanguage, IReadOnlyList sentencesLengths, IDictionary serializedAdditionalRawData) + internal BreakSentenceItem(DetectedLanguage detectedLanguage, IReadOnlyList sentLen, IDictionary serializedAdditionalRawData) { DetectedLanguage = detectedLanguage; - SentencesLengths = sentencesLengths; + SentLen = sentLen; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -84,6 +84,6 @@ internal BreakSentenceItem() /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - public IReadOnlyList SentencesLengths { get; } + public IReadOnlyList SentLen { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.Serialization.cs index 2f41f3486b7a..8986a4f6b236 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.Serialization.cs @@ -37,7 +37,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("language"u8); writer.WriteStringValue(Language); writer.WritePropertyName("score"u8); - writer.WriteNumberValue(Confidence); + writer.WriteNumberValue(Score); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.cs index 22b9c2194b90..3be254c3db19 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/DetectedLanguage.cs @@ -47,30 +47,30 @@ public partial class DetectedLanguage /// Initializes a new instance of . /// A string representing the code of the detected language. - /// + /// /// A float value indicating the confidence in the result. /// The score is between zero and one and a low score indicates a low confidence. /// /// is null. - internal DetectedLanguage(string language, float confidence) + internal DetectedLanguage(string language, float score) { Argument.AssertNotNull(language, nameof(language)); Language = language; - Confidence = confidence; + Score = score; } /// Initializes a new instance of . /// A string representing the code of the detected language. - /// + /// /// A float value indicating the confidence in the result. /// The score is between zero and one and a low score indicates a low confidence. /// /// Keeps track of any properties unknown to the library. - internal DetectedLanguage(string language, float confidence, IDictionary serializedAdditionalRawData) + internal DetectedLanguage(string language, float score, IDictionary serializedAdditionalRawData) { Language = language; - Confidence = confidence; + Score = score; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -85,6 +85,6 @@ internal DetectedLanguage() /// A float value indicating the confidence in the result. /// The score is between zero and one and a low score indicates a low confidence. /// - public float Confidence { get; } + public float Score { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.Serialization.cs index f4878c316a0e..f1ac03b5eaeb 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.Serialization.cs @@ -41,7 +41,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("nativeName"u8); writer.WriteStringValue(NativeName); writer.WritePropertyName("dir"u8); - writer.WriteStringValue(Directionality.ToSerialString()); + writer.WriteStringValue(Dir.ToSerialString()); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.cs index 94eb100e4809..314371ec9c64 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/LanguageScript.cs @@ -49,9 +49,9 @@ public partial class LanguageScript /// Code identifying the script. /// Display name of the script in the locale requested via Accept-Language header. /// Display name of the language in the locale native for the language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// , or is null. - internal LanguageScript(string code, string name, string nativeName, LanguageDirectionality directionality) + internal LanguageScript(string code, string name, string nativeName, LanguageDirectionality dir) { Argument.AssertNotNull(code, nameof(code)); Argument.AssertNotNull(name, nameof(name)); @@ -60,21 +60,21 @@ internal LanguageScript(string code, string name, string nativeName, LanguageDir Code = code; Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; } /// Initializes a new instance of . /// Code identifying the script. /// Display name of the script in the locale requested via Accept-Language header. /// Display name of the language in the locale native for the language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// Keeps track of any properties unknown to the library. - internal LanguageScript(string code, string name, string nativeName, LanguageDirectionality directionality, IDictionary serializedAdditionalRawData) + internal LanguageScript(string code, string name, string nativeName, LanguageDirectionality dir, IDictionary serializedAdditionalRawData) { Code = code; Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -90,6 +90,6 @@ internal LanguageScript() /// Display name of the language in the locale native for the language. public string NativeName { get; } /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - public LanguageDirectionality Directionality { get; } + public LanguageDirectionality Dir { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.Serialization.cs index 59bbe075d0a3..7003b22d4a9f 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.Serialization.cs @@ -36,14 +36,14 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("srcSentLen"u8); writer.WriteStartArray(); - foreach (var item in SourceSentencesLengths) + foreach (var item in SrcSentLen) { writer.WriteNumberValue(item); } writer.WriteEndArray(); writer.WritePropertyName("transSentLen"u8); writer.WriteStartArray(); - foreach (var item in TranslatedSentencesLengths) + foreach (var item in TransSentLen) { writer.WriteNumberValue(item); } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.cs index 70fd3b61c965..b800a077525d 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SentenceBoundaries.cs @@ -47,38 +47,38 @@ public partial class SentenceBoundaries private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// + /// /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - /// + /// /// An integer array representing the lengths of the sentences in the translated text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - /// or is null. - internal SentenceBoundaries(IEnumerable sourceSentencesLengths, IEnumerable translatedSentencesLengths) + /// or is null. + internal SentenceBoundaries(IEnumerable srcSentLen, IEnumerable transSentLen) { - Argument.AssertNotNull(sourceSentencesLengths, nameof(sourceSentencesLengths)); - Argument.AssertNotNull(translatedSentencesLengths, nameof(translatedSentencesLengths)); + Argument.AssertNotNull(srcSentLen, nameof(srcSentLen)); + Argument.AssertNotNull(transSentLen, nameof(transSentLen)); - SourceSentencesLengths = sourceSentencesLengths.ToList(); - TranslatedSentencesLengths = translatedSentencesLengths.ToList(); + SrcSentLen = srcSentLen.ToList(); + TransSentLen = transSentLen.ToList(); } /// Initializes a new instance of . - /// + /// /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - /// + /// /// An integer array representing the lengths of the sentences in the translated text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// /// Keeps track of any properties unknown to the library. - internal SentenceBoundaries(IReadOnlyList sourceSentencesLengths, IReadOnlyList translatedSentencesLengths, IDictionary serializedAdditionalRawData) + internal SentenceBoundaries(IReadOnlyList srcSentLen, IReadOnlyList transSentLen, IDictionary serializedAdditionalRawData) { - SourceSentencesLengths = sourceSentencesLengths; - TranslatedSentencesLengths = translatedSentencesLengths; + SrcSentLen = srcSentLen; + TransSentLen = transSentLen; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -91,11 +91,11 @@ internal SentenceBoundaries() /// An integer array representing the lengths of the sentences in the input text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - public IReadOnlyList SourceSentencesLengths { get; } + public IReadOnlyList SrcSentLen { get; } /// /// An integer array representing the lengths of the sentences in the translated text. /// The length of the array is the number of sentences, and the values are the length of each sentence. /// - public IReadOnlyList TranslatedSentencesLengths { get; } + public IReadOnlyList TransSentLen { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.Serialization.cs index d9b45a50b6bc..a7634627f3c5 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.Serialization.cs @@ -39,7 +39,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("nativeName"u8); writer.WriteStringValue(NativeName); writer.WritePropertyName("dir"u8); - writer.WriteStringValue(Directionality.ToSerialString()); + writer.WriteStringValue(Dir.ToSerialString()); writer.WritePropertyName("translations"u8); writer.WriteStartArray(); foreach (var item in Translations) diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.cs index cf0a057a1b7b..4ab55b7eac91 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/SourceDictionaryLanguage.cs @@ -49,10 +49,10 @@ public partial class SourceDictionaryLanguage /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// List of languages with alterative translations and examples for the query expressed in the source language. /// , or is null. - internal SourceDictionaryLanguage(string name, string nativeName, LanguageDirectionality directionality, IEnumerable translations) + internal SourceDictionaryLanguage(string name, string nativeName, LanguageDirectionality dir, IEnumerable translations) { Argument.AssertNotNull(name, nameof(name)); Argument.AssertNotNull(nativeName, nameof(nativeName)); @@ -60,21 +60,21 @@ internal SourceDictionaryLanguage(string name, string nativeName, LanguageDirect Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; Translations = translations.ToList(); } /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// List of languages with alterative translations and examples for the query expressed in the source language. /// Keeps track of any properties unknown to the library. - internal SourceDictionaryLanguage(string name, string nativeName, LanguageDirectionality directionality, IReadOnlyList translations, IDictionary serializedAdditionalRawData) + internal SourceDictionaryLanguage(string name, string nativeName, LanguageDirectionality dir, IReadOnlyList translations, IDictionary serializedAdditionalRawData) { Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; Translations = translations; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -89,7 +89,7 @@ internal SourceDictionaryLanguage() /// Display name of the language in the locale native for this language. public string NativeName { get; } /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - public LanguageDirectionality Directionality { get; } + public LanguageDirectionality Dir { get; } /// List of languages with alterative translations and examples for the query expressed in the source language. public IReadOnlyList Translations { get; } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.Serialization.cs index 85add6867f99..c70fb22ded00 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.Serialization.cs @@ -39,7 +39,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("nativeName"u8); writer.WriteStringValue(NativeName); writer.WritePropertyName("dir"u8); - writer.WriteStringValue(Directionality.ToSerialString()); + writer.WriteStringValue(Dir.ToSerialString()); writer.WritePropertyName("code"u8); writer.WriteStringValue(Code); if (options.Format != "W" && _serializedAdditionalRawData != null) diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.cs index 81845ba309e5..c296c28456bf 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TargetDictionaryLanguage.cs @@ -48,10 +48,10 @@ public partial class TargetDictionaryLanguage /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// Language code identifying the target language. /// , or is null. - internal TargetDictionaryLanguage(string name, string nativeName, LanguageDirectionality directionality, string code) + internal TargetDictionaryLanguage(string name, string nativeName, LanguageDirectionality dir, string code) { Argument.AssertNotNull(name, nameof(name)); Argument.AssertNotNull(nativeName, nameof(nativeName)); @@ -59,21 +59,21 @@ internal TargetDictionaryLanguage(string name, string nativeName, LanguageDirect Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; Code = code; } /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// Language code identifying the target language. /// Keeps track of any properties unknown to the library. - internal TargetDictionaryLanguage(string name, string nativeName, LanguageDirectionality directionality, string code, IDictionary serializedAdditionalRawData) + internal TargetDictionaryLanguage(string name, string nativeName, LanguageDirectionality dir, string code, IDictionary serializedAdditionalRawData) { Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; Code = code; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -88,7 +88,7 @@ internal TargetDictionaryLanguage() /// Display name of the language in the locale native for this language. public string NativeName { get; } /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - public LanguageDirectionality Directionality { get; } + public LanguageDirectionality Dir { get; } /// Language code identifying the target language. public string Code { get; } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TextTranslationClient.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TextTranslationClient.cs index a109230e24f6..d7c7f89e113c 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TextTranslationClient.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TextTranslationClient.cs @@ -252,7 +252,7 @@ internal HttpMessage CreateGetSupportedLanguagesRequest(string clientTraceId, st return message; } - internal HttpMessage CreateTranslateRequest(IEnumerable targetLanguages, RequestContent content, string clientTraceId, string sourceLanguage, string textType, string category, string profanityAction, string profanityMarker, bool? includeAlignment, bool? includeSentenceLength, string suggestedSourceLanguage, string sourceLanguageScript, string targetLanguageScript, bool? allowFallback, RequestContext context) + internal HttpMessage CreateTranslateRequest(IEnumerable to, RequestContent content, string clientTraceId, string @from, string textType, string category, string profanityAction, string profanityMarker, bool? includeAlignment, bool? includeSentenceLength, string suggestedFrom, string fromScript, string toScript, bool? allowFallback, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; @@ -260,16 +260,16 @@ internal HttpMessage CreateTranslateRequest(IEnumerable targetLanguages, var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/translate", false); - if (targetLanguages != null && !(targetLanguages is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) + if (to != null && !(to is ChangeTrackingList changeTrackingList && changeTrackingList.IsUndefined)) { - foreach (var param in targetLanguages) + foreach (var param in to) { uri.AppendQuery("to", param, true); } } - if (sourceLanguage != null) + if (@from != null) { - uri.AppendQuery("from", sourceLanguage, true); + uri.AppendQuery("from", @from, true); } if (textType != null) { @@ -295,17 +295,17 @@ internal HttpMessage CreateTranslateRequest(IEnumerable targetLanguages, { uri.AppendQuery("includeSentenceLength", includeSentenceLength.Value, true); } - if (suggestedSourceLanguage != null) + if (suggestedFrom != null) { - uri.AppendQuery("suggestedFrom", suggestedSourceLanguage, true); + uri.AppendQuery("suggestedFrom", suggestedFrom, true); } - if (sourceLanguageScript != null) + if (fromScript != null) { - uri.AppendQuery("fromScript", sourceLanguageScript, true); + uri.AppendQuery("fromScript", fromScript, true); } - if (targetLanguageScript != null) + if (toScript != null) { - uri.AppendQuery("toScript", targetLanguageScript, true); + uri.AppendQuery("toScript", toScript, true); } if (allowFallback != null) { @@ -323,7 +323,7 @@ internal HttpMessage CreateTranslateRequest(IEnumerable targetLanguages, return message; } - internal HttpMessage CreateTransliterateRequest(string language, string sourceLanguageScript, string targetLanguageScript, RequestContent content, string clientTraceId, RequestContext context) + internal HttpMessage CreateTransliterateRequest(string language, string fromScript, string toScript, RequestContent content, string clientTraceId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; @@ -332,8 +332,8 @@ internal HttpMessage CreateTransliterateRequest(string language, string sourceLa uri.Reset(_endpoint); uri.AppendPath("/transliterate", false); uri.AppendQuery("language", language, true); - uri.AppendQuery("fromScript", sourceLanguageScript, true); - uri.AppendQuery("toScript", targetLanguageScript, true); + uri.AppendQuery("fromScript", fromScript, true); + uri.AppendQuery("toScript", toScript, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); @@ -374,7 +374,7 @@ internal HttpMessage CreateFindSentenceBoundariesRequest(RequestContent content, return message; } - internal HttpMessage CreateLookupDictionaryEntriesRequest(string sourceLanguage, string targetLanguage, RequestContent content, string clientTraceId, RequestContext context) + internal HttpMessage CreateLookupDictionaryEntriesRequest(string @from, string to, RequestContent content, string clientTraceId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; @@ -382,8 +382,8 @@ internal HttpMessage CreateLookupDictionaryEntriesRequest(string sourceLanguage, var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/dictionary/lookup", false); - uri.AppendQuery("from", sourceLanguage, true); - uri.AppendQuery("to", targetLanguage, true); + uri.AppendQuery("from", @from, true); + uri.AppendQuery("to", to, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); @@ -396,7 +396,7 @@ internal HttpMessage CreateLookupDictionaryEntriesRequest(string sourceLanguage, return message; } - internal HttpMessage CreateLookupDictionaryExamplesRequest(string sourceLanguage, string targetLanguage, RequestContent content, string clientTraceId, RequestContext context) + internal HttpMessage CreateLookupDictionaryExamplesRequest(string @from, string to, RequestContent content, string clientTraceId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; @@ -404,8 +404,8 @@ internal HttpMessage CreateLookupDictionaryExamplesRequest(string sourceLanguage var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/dictionary/examples", false); - uri.AppendQuery("from", sourceLanguage, true); - uri.AppendQuery("to", targetLanguage, true); + uri.AppendQuery("from", @from, true); + uri.AppendQuery("to", to, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.Serialization.cs index b8c4a686ce3e..e5d5691b21b9 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.Serialization.cs @@ -35,7 +35,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName("proj"u8); - writer.WriteStringValue(Projections); + writer.WriteStringValue(Proj); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.cs index 410a73875cfe..0d697a283a56 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslatedTextAlignment.cs @@ -46,7 +46,7 @@ public partial class TranslatedTextAlignment private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// + /// /// Maps input text to translated text. The alignment information is only provided when the request /// parameter includeAlignment is true. Alignment is returned as a string value of the following /// format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. @@ -54,16 +54,16 @@ public partial class TranslatedTextAlignment /// One word may align with zero, one, or multiple words in the other language, and the aligned words may /// be non-contiguous. When no alignment information is available, the alignment element will be empty. /// - /// is null. - internal TranslatedTextAlignment(string projections) + /// is null. + internal TranslatedTextAlignment(string proj) { - Argument.AssertNotNull(projections, nameof(projections)); + Argument.AssertNotNull(proj, nameof(proj)); - Projections = projections; + Proj = proj; } /// Initializes a new instance of . - /// + /// /// Maps input text to translated text. The alignment information is only provided when the request /// parameter includeAlignment is true. Alignment is returned as a string value of the following /// format: [[SourceTextStartIndex]:[SourceTextEndIndex]–[TgtTextStartIndex]:[TgtTextEndIndex]]. @@ -72,9 +72,9 @@ internal TranslatedTextAlignment(string projections) /// be non-contiguous. When no alignment information is available, the alignment element will be empty. /// /// Keeps track of any properties unknown to the library. - internal TranslatedTextAlignment(string projections, IDictionary serializedAdditionalRawData) + internal TranslatedTextAlignment(string proj, IDictionary serializedAdditionalRawData) { - Projections = projections; + Proj = proj; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -91,6 +91,6 @@ internal TranslatedTextAlignment() /// One word may align with zero, one, or multiple words in the other language, and the aligned words may /// be non-contiguous. When no alignment information is available, the alignment element will be empty. /// - public string Projections { get; } + public string Proj { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.Serialization.cs index a24758b297e6..3af71d78a490 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.Serialization.cs @@ -39,7 +39,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("nativeName"u8); writer.WriteStringValue(NativeName); writer.WritePropertyName("dir"u8); - writer.WriteStringValue(Directionality.ToSerialString()); + writer.WriteStringValue(Dir.ToSerialString()); if (options.Format != "W" && _serializedAdditionalRawData != null) { foreach (var item in _serializedAdditionalRawData) diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.cs index 9fe1669f9945..3f73d4dfb717 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationLanguage.cs @@ -51,28 +51,28 @@ public partial class TranslationLanguage /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// or is null. - internal TranslationLanguage(string name, string nativeName, LanguageDirectionality directionality) + internal TranslationLanguage(string name, string nativeName, LanguageDirectionality dir) { Argument.AssertNotNull(name, nameof(name)); Argument.AssertNotNull(nativeName, nameof(nativeName)); Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; } /// Initializes a new instance of . /// Display name of the language in the locale requested via Accept-Language header. /// Display name of the language in the locale native for this language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// Keeps track of any properties unknown to the library. - internal TranslationLanguage(string name, string nativeName, LanguageDirectionality directionality, IDictionary serializedAdditionalRawData) + internal TranslationLanguage(string name, string nativeName, LanguageDirectionality dir, IDictionary serializedAdditionalRawData) { Name = name; NativeName = nativeName; - Directionality = directionality; + Dir = dir; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -86,6 +86,6 @@ internal TranslationLanguage() /// Display name of the language in the locale native for this language. public string NativeName { get; } /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - public LanguageDirectionality Directionality { get; } + public LanguageDirectionality Dir { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.Serialization.cs index 0b2d6845fe93..d4133aaca421 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.Serialization.cs @@ -35,7 +35,7 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit } writer.WritePropertyName("to"u8); - writer.WriteStringValue(TargetLanguage); + writer.WriteStringValue(To); writer.WritePropertyName("text"u8); writer.WriteStringValue(Text); if (Optional.IsDefined(Transliteration)) @@ -48,10 +48,10 @@ protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWrit writer.WritePropertyName("alignment"u8); writer.WriteObjectValue(Alignment, options); } - if (Optional.IsDefined(SentenceBoundaries)) + if (Optional.IsDefined(SentLen)) { writer.WritePropertyName("sentLen"u8); - writer.WriteObjectValue(SentenceBoundaries, options); + writer.WriteObjectValue(SentLen, options); } if (options.Format != "W" && _serializedAdditionalRawData != null) { diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.cs index e283bbf676d4..ea46814957e7 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TranslationText.cs @@ -46,32 +46,32 @@ public partial class TranslationText private IDictionary _serializedAdditionalRawData; /// Initializes a new instance of . - /// A string representing the language code of the target language. + /// A string representing the language code of the target language. /// A string giving the translated text. - /// or is null. - internal TranslationText(string targetLanguage, string text) + /// or is null. + internal TranslationText(string to, string text) { - Argument.AssertNotNull(targetLanguage, nameof(targetLanguage)); + Argument.AssertNotNull(to, nameof(to)); Argument.AssertNotNull(text, nameof(text)); - TargetLanguage = targetLanguage; + To = to; Text = text; } /// Initializes a new instance of . - /// A string representing the language code of the target language. + /// A string representing the language code of the target language. /// A string giving the translated text. /// An object giving the translated text in the script specified by the toScript parameter. /// Alignment information. - /// Sentence boundaries in the input and output texts. + /// Sentence boundaries in the input and output texts. /// Keeps track of any properties unknown to the library. - internal TranslationText(string targetLanguage, string text, TransliteratedText transliteration, TranslatedTextAlignment alignment, SentenceBoundaries sentenceBoundaries, IDictionary serializedAdditionalRawData) + internal TranslationText(string to, string text, TransliteratedText transliteration, TranslatedTextAlignment alignment, SentenceBoundaries sentLen, IDictionary serializedAdditionalRawData) { - TargetLanguage = targetLanguage; + To = to; Text = text; Transliteration = transliteration; Alignment = alignment; - SentenceBoundaries = sentenceBoundaries; + SentLen = sentLen; _serializedAdditionalRawData = serializedAdditionalRawData; } @@ -81,7 +81,7 @@ internal TranslationText() } /// A string representing the language code of the target language. - public string TargetLanguage { get; } + public string To { get; } /// A string giving the translated text. public string Text { get; } /// An object giving the translated text in the script specified by the toScript parameter. @@ -89,6 +89,6 @@ internal TranslationText() /// Alignment information. public TranslatedTextAlignment Alignment { get; } /// Sentence boundaries in the input and output texts. - public SentenceBoundaries SentenceBoundaries { get; } + public SentenceBoundaries SentLen { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.Serialization.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.Serialization.cs index ad9e691d44b0..3070c972c449 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.Serialization.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.Serialization.cs @@ -37,7 +37,7 @@ protected override void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWri base.JsonModelWriteCore(writer, options); writer.WritePropertyName("toScripts"u8); writer.WriteStartArray(); - foreach (var item in TargetLanguageScripts) + foreach (var item in ToScripts) { writer.WriteObjectValue(item, options); } diff --git a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.cs b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.cs index 24de9ee02a96..9297e7b27e47 100644 --- a/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.cs +++ b/sdk/translation/Azure.AI.Translation.Text/src/Generated/TransliterableScript.cs @@ -18,29 +18,29 @@ public partial class TransliterableScript : LanguageScript /// Code identifying the script. /// Display name of the script in the locale requested via Accept-Language header. /// Display name of the language in the locale native for the language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. - /// List of scripts available to convert text to. - /// , , or is null. - internal TransliterableScript(string code, string name, string nativeName, LanguageDirectionality directionality, IEnumerable targetLanguageScripts) : base(code, name, nativeName, directionality) + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// List of scripts available to convert text to. + /// , , or is null. + internal TransliterableScript(string code, string name, string nativeName, LanguageDirectionality dir, IEnumerable toScripts) : base(code, name, nativeName, dir) { Argument.AssertNotNull(code, nameof(code)); Argument.AssertNotNull(name, nameof(name)); Argument.AssertNotNull(nativeName, nameof(nativeName)); - Argument.AssertNotNull(targetLanguageScripts, nameof(targetLanguageScripts)); + Argument.AssertNotNull(toScripts, nameof(toScripts)); - TargetLanguageScripts = targetLanguageScripts.ToList(); + ToScripts = toScripts.ToList(); } /// Initializes a new instance of . /// Code identifying the script. /// Display name of the script in the locale requested via Accept-Language header. /// Display name of the language in the locale native for the language. - /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. + /// Directionality, which is rtl for right-to-left languages or ltr for left-to-right languages. /// Keeps track of any properties unknown to the library. - /// List of scripts available to convert text to. - internal TransliterableScript(string code, string name, string nativeName, LanguageDirectionality directionality, IDictionary serializedAdditionalRawData, IReadOnlyList targetLanguageScripts) : base(code, name, nativeName, directionality, serializedAdditionalRawData) + /// List of scripts available to convert text to. + internal TransliterableScript(string code, string name, string nativeName, LanguageDirectionality dir, IDictionary serializedAdditionalRawData, IReadOnlyList toScripts) : base(code, name, nativeName, dir, serializedAdditionalRawData) { - TargetLanguageScripts = targetLanguageScripts; + ToScripts = toScripts; } /// Initializes a new instance of for deserialization. @@ -49,6 +49,6 @@ internal TransliterableScript() } /// List of scripts available to convert text to. - public IReadOnlyList TargetLanguageScripts { get; } + public IReadOnlyList ToScripts { get; } } } diff --git a/sdk/translation/Azure.AI.Translation.Text/tsp-location.yaml b/sdk/translation/Azure.AI.Translation.Text/tsp-location.yaml index 841608896612..e203f03c9c54 100644 --- a/sdk/translation/Azure.AI.Translation.Text/tsp-location.yaml +++ b/sdk/translation/Azure.AI.Translation.Text/tsp-location.yaml @@ -1,3 +1,4 @@ directory: specification/translation/Azure.AI.TextTranslation -commit: eeb8d28f3dcc630e8eb99e10e0bfb371b4b22509 +commit: eaaef41ddeb7e5e2f4025c7ce714c4a36f06dcd5 repo: Azure/azure-rest-api-specs +additionalDirectories: