diff --git a/sdk/ai/azure-ai-projects-onedp/apiview-properties.json b/sdk/ai/azure-ai-projects-onedp/apiview-properties.json index c93a0c90f921..0365ccce083b 100644 --- a/sdk/ai/azure-ai-projects-onedp/apiview-properties.json +++ b/sdk/ai/azure-ai-projects-onedp/apiview-properties.json @@ -1,16 +1,19 @@ { "CrossLanguagePackageId": "Azure.AI.Projects", "CrossLanguageDefinitionId": { + "azure.ai.projects.onedp.models.BaseCredentials": "Azure.AI.Projects.BaseCredentials", + "azure.ai.projects.onedp.models.ApiKeyCredentials": "Azure.AI.Projects.ApiKeyCredentials", "azure.ai.projects.onedp.models.Index": "Azure.AI.Projects.Index", "azure.ai.projects.onedp.models.AzureAISearchIndex": "Azure.AI.Projects.AzureAISearchIndex", "azure.ai.projects.onedp.models.BlobReferenceForConsumption": "Azure.AI.Projects.BlobReferenceForConsumption", "azure.ai.projects.onedp.models.Connection": "Azure.AI.Projects.Connection", "azure.ai.projects.onedp.models.CosmosDBIndex": "Azure.AI.Projects.CosmosDBIndex", + "azure.ai.projects.onedp.models.CustomCredential": "Azure.AI.Projects.CustomCredential", "azure.ai.projects.onedp.models.DatasetVersion": "Azure.AI.Projects.DatasetVersion", "azure.ai.projects.onedp.models.Deployment": "Azure.AI.Projects.Deployment", "azure.ai.projects.onedp.models.EmbeddingConfiguration": "Azure.AI.Projects.EmbeddingConfiguration", + "azure.ai.projects.onedp.models.EntraIDCredentials": "Azure.AI.Projects.EntraIDCredentials", "azure.ai.projects.onedp.models.Evaluation": "Azure.AI.Projects.Evaluation", - "azure.ai.projects.onedp.models.EvaluationResult": "Azure.AI.Projects.EvaluationResult", "azure.ai.projects.onedp.models.EvaluatorConfiguration": "Azure.AI.Projects.EvaluatorConfiguration", "azure.ai.projects.onedp.models.FileDatasetVersion": "Azure.AI.Projects.FileDatasetVersion", "azure.ai.projects.onedp.models.FolderDatasetVersion": "Azure.AI.Projects.FolderDatasetVersion", @@ -18,23 +21,24 @@ "azure.ai.projects.onedp.models.InputDataset": "Azure.AI.Projects.InputDataset", "azure.ai.projects.onedp.models.ManagedAzureAISearchIndex": "Azure.AI.Projects.ManagedAzureAISearchIndex", "azure.ai.projects.onedp.models.ModelDeployment": "Azure.AI.Projects.ModelDeployment", + "azure.ai.projects.onedp.models.NoAuthenticationCredentials": "Azure.AI.Projects.NoAuthenticationCredentials", "azure.ai.projects.onedp.models.PendingUploadRequest": "Azure.AI.Projects.PendingUploadRequest", "azure.ai.projects.onedp.models.PendingUploadResponse": "Azure.AI.Projects.PendingUploadResponse", "azure.ai.projects.onedp.models.RedTeam": "Azure.AI.Projects.RedTeam", "azure.ai.projects.onedp.models.SasCredential": "Azure.AI.Projects.SasCredential", + "azure.ai.projects.onedp.models.SASCredentials": "Azure.AI.Projects.SASCredentials", "azure.ai.projects.onedp.models.Sku": "Azure.AI.Projects.Sku", "azure.ai.projects.onedp.models.ConnectionType": "Azure.AI.Projects.ConnectionType", - "azure.ai.projects.onedp.models.AuthenticationType": "Azure.AI.Projects.AuthenticationType", + "azure.ai.projects.onedp.models.CredentialType": "Azure.AI.Projects.CredentialType", "azure.ai.projects.onedp.models.DatasetType": "Azure.AI.Projects.DatasetType", "azure.ai.projects.onedp.models.ListViewType": "Azure.AI.Projects.ListViewType", - "azure.ai.projects.onedp.models.RepeatabilityResult": "Azure.Core.RepeatabilityResult", "azure.ai.projects.onedp.models.PendingUploadType": "Azure.AI.Projects.PendingUploadType", "azure.ai.projects.onedp.models.IndexType": "Azure.AI.Projects.IndexType", "azure.ai.projects.onedp.models.DeploymentType": "Azure.AI.Projects.DeploymentType", - "azure.ai.projects.onedp.models.ResultType": "Azure.AI.Projects.ResultType", "azure.ai.projects.onedp.models.AttackStrategy": "Azure.AI.Projects.AttackStrategy", "azure.ai.projects.onedp.models.RiskCategory": "Azure.AI.Projects.RiskCategory", "azure.ai.projects.onedp.AIProjectClient.connections.get": "Azure.AI.Projects.Connections.get", + "azure.ai.projects.onedp.AIProjectClient.connections.get_with_credentials": "Azure.AI.Projects.Connections.getWithCredentials", "azure.ai.projects.onedp.AIProjectClient.connections.list": "Azure.AI.Projects.Connections.list", "azure.ai.projects.onedp.AIProjectClient.evaluations.get": "Azure.AI.Projects.Evaluations.get", "azure.ai.projects.onedp.AIProjectClient.evaluations.list": "Azure.AI.Projects.Evaluations.list", @@ -43,25 +47,15 @@ "azure.ai.projects.onedp.AIProjectClient.datasets.list_latest": "Azure.AI.Projects.ServicePatterns.Datasets.listLatest", "azure.ai.projects.onedp.AIProjectClient.datasets.get_version": "Azure.AI.Projects.ServicePatterns.Datasets.getVersion", "azure.ai.projects.onedp.AIProjectClient.datasets.delete_version": "Azure.AI.Projects.ServicePatterns.Datasets.deleteVersion", - "azure.ai.projects.onedp.AIProjectClient.datasets.create": "Azure.AI.Projects.ServicePatterns.Datasets.create", "azure.ai.projects.onedp.AIProjectClient.datasets.create_version": "Azure.AI.Projects.ServicePatterns.Datasets.createVersion", "azure.ai.projects.onedp.AIProjectClient.datasets.start_pending_upload_version": "Azure.AI.Projects.Datasets.startPendingUploadVersion", - "azure.ai.projects.onedp.AIProjectClient.datasets.start_pending_upload": "Azure.AI.Projects.Datasets.startPendingUpload", "azure.ai.projects.onedp.AIProjectClient.indexes.list_versions": "Azure.AI.Projects.ServicePatterns.Indexes.listVersions", "azure.ai.projects.onedp.AIProjectClient.indexes.list_latest": "Azure.AI.Projects.ServicePatterns.Indexes.listLatest", "azure.ai.projects.onedp.AIProjectClient.indexes.get_version": "Azure.AI.Projects.ServicePatterns.Indexes.getVersion", "azure.ai.projects.onedp.AIProjectClient.indexes.delete_version": "Azure.AI.Projects.ServicePatterns.Indexes.deleteVersion", - "azure.ai.projects.onedp.AIProjectClient.indexes.create": "Azure.AI.Projects.ServicePatterns.Indexes.create", "azure.ai.projects.onedp.AIProjectClient.indexes.create_version": "Azure.AI.Projects.ServicePatterns.Indexes.createVersion", "azure.ai.projects.onedp.AIProjectClient.deployments.get": "Azure.AI.Projects.Deployments.get", "azure.ai.projects.onedp.AIProjectClient.deployments.list": "Azure.AI.Projects.Deployments.list", - "azure.ai.projects.onedp.AIProjectClient.evaluation_results.list_versions": "Azure.AI.Projects.ServicePatterns.EvaluationResults.listVersions", - "azure.ai.projects.onedp.AIProjectClient.evaluation_results.list_latest": "Azure.AI.Projects.ServicePatterns.EvaluationResults.listLatest", - "azure.ai.projects.onedp.AIProjectClient.evaluation_results.get_version": "Azure.AI.Projects.ServicePatterns.EvaluationResults.getVersion", - "azure.ai.projects.onedp.AIProjectClient.evaluation_results.delete_version": "Azure.AI.Projects.ServicePatterns.EvaluationResults.deleteVersion", - "azure.ai.projects.onedp.AIProjectClient.evaluation_results.create": "Azure.AI.Projects.ServicePatterns.EvaluationResults.create", - "azure.ai.projects.onedp.AIProjectClient.evaluation_results.create_version": "Azure.AI.Projects.ServicePatterns.EvaluationResults.createVersion", - "azure.ai.projects.onedp.AIProjectClient.evaluation_results.start_pending_upload": "Azure.AI.Projects.EvaluationResults.startPendingUpload", "azure.ai.projects.onedp.AIProjectClient.red_teams.get": "Azure.AI.Projects.RedTeams.get", "azure.ai.projects.onedp.AIProjectClient.red_teams.list": "Azure.AI.Projects.RedTeams.list", "azure.ai.projects.onedp.AIProjectClient.red_teams.create_run": "Azure.AI.Projects.RedTeams.createRun" diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_client.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_client.py index 78f6c499f1c8..27a54a66bf4f 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_client.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_client.py @@ -21,7 +21,6 @@ ConnectionsOperations, DatasetsOperations, DeploymentsOperations, - EvaluationResultsOperations, EvaluationsOperations, IndexesOperations, RedTeamsOperations, @@ -47,8 +46,6 @@ class AIProjectClient: # pylint: disable=too-many-instance-attributes :vartype indexes: azure.ai.projects.onedp.operations.IndexesOperations :ivar deployments: DeploymentsOperations operations :vartype deployments: azure.ai.projects.onedp.operations.DeploymentsOperations - :ivar evaluation_results: EvaluationResultsOperations operations - :vartype evaluation_results: azure.ai.projects.onedp.operations.EvaluationResultsOperations :ivar red_teams: RedTeamsOperations operations :vartype red_teams: azure.ai.projects.onedp.operations.RedTeamsOperations :param endpoint: Project endpoint in the form of: @@ -97,9 +94,6 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCr self.datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) self.deployments = DeploymentsOperations(self._client, self._config, self._serialize, self._deserialize) - self.evaluation_results = EvaluationResultsOperations( - self._client, self._config, self._serialize, self._deserialize - ) self.red_teams = RedTeamsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_patch.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_patch.py index 846ca97d34d0..e7188a84a7e0 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_patch.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/_patch.py @@ -9,7 +9,8 @@ from typing import List, Any, Union, Optional from azure.core.credentials import AzureKeyCredential from ._client import AIProjectClient as AIProjectClientGenerated -from .operations import TelemetryOperations, InferenceOperations +from .operations import TelemetryOperations, InferenceOperations, AssistantsOperations + class AIProjectClient(AIProjectClientGenerated): # pylint: disable=too-many-instance-attributes """AIProjectClient. @@ -48,11 +49,10 @@ def __init__(self, endpoint: str, credential: Union[AzureKeyCredential, "TokenCr super().__init__(endpoint=endpoint, credential=credential, **kwargs) self.telemetry = TelemetryOperations(self) self.inference = InferenceOperations(self) + self.assistants = AssistantsOperations(self) -__all__: List[str] = [ - "AIProjectClient" -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = ["AIProjectClient"] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_client.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_client.py index 6b2ebc4df943..e7779e2cf92b 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_client.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_client.py @@ -21,7 +21,6 @@ ConnectionsOperations, DatasetsOperations, DeploymentsOperations, - EvaluationResultsOperations, EvaluationsOperations, IndexesOperations, RedTeamsOperations, @@ -47,8 +46,6 @@ class AIProjectClient: # pylint: disable=too-many-instance-attributes :vartype indexes: azure.ai.projects.onedp.aio.operations.IndexesOperations :ivar deployments: DeploymentsOperations operations :vartype deployments: azure.ai.projects.onedp.aio.operations.DeploymentsOperations - :ivar evaluation_results: EvaluationResultsOperations operations - :vartype evaluation_results: azure.ai.projects.onedp.aio.operations.EvaluationResultsOperations :ivar red_teams: RedTeamsOperations operations :vartype red_teams: azure.ai.projects.onedp.aio.operations.RedTeamsOperations :param endpoint: Project endpoint in the form of: @@ -99,9 +96,6 @@ def __init__( self.datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) self.deployments = DeploymentsOperations(self._client, self._config, self._serialize, self._deserialize) - self.evaluation_results = EvaluationResultsOperations( - self._client, self._config, self._serialize, self._deserialize - ) self.red_teams = RedTeamsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_patch.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_patch.py index e28f59b7aba1..df5f988b6da5 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_patch.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/_patch.py @@ -9,7 +9,8 @@ from typing import List, Optional, Union, Any from azure.core.credentials import AzureKeyCredential from ._client import AIProjectClient as AIProjectClientGenerated -from .operations import InferenceOperations +from .operations import InferenceOperations, AssistantsOperations, TelemetryOperations + class AIProjectClient(AIProjectClientGenerated): # pylint: disable=too-many-instance-attributes """AIProjectClient. @@ -48,12 +49,12 @@ def __init__( ) -> None: self._user_agent: Optional[str] = kwargs.get("user_agent", None) super().__init__(endpoint=endpoint, credential=credential, **kwargs) + self.telemetry = TelemetryOperations(self) self.inference = InferenceOperations(self) + self.assistants = AssistantsOperations(self) -__all__: List[str] = [ - "AIProjectClient" -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = ["AIProjectClient"] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/__init__.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/__init__.py index f6be99bbed9c..c8b497b4854b 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/__init__.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/__init__.py @@ -18,7 +18,6 @@ from ._operations import DatasetsOperations # type: ignore from ._operations import IndexesOperations # type: ignore from ._operations import DeploymentsOperations # type: ignore -from ._operations import EvaluationResultsOperations # type: ignore from ._operations import RedTeamsOperations # type: ignore from ._patch import __all__ as _patch_all @@ -32,7 +31,6 @@ "DatasetsOperations", "IndexesOperations", "DeploymentsOperations", - "EvaluationResultsOperations", "RedTeamsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_operations.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_operations.py index 480f52e3c34e..1299b6fdaed3 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_operations.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_operations.py @@ -36,28 +36,19 @@ from ..._validation import api_version_validation from ...operations._operations import ( build_connections_get_request, + build_connections_get_with_credentials_request, build_connections_list_request, - build_datasets_create_request, build_datasets_create_version_request, build_datasets_delete_version_request, build_datasets_get_version_request, build_datasets_list_latest_request, build_datasets_list_versions_request, - build_datasets_start_pending_upload_request, build_datasets_start_pending_upload_version_request, build_deployments_get_request, build_deployments_list_request, - build_evaluation_results_create_request, - build_evaluation_results_create_version_request, - build_evaluation_results_delete_version_request, - build_evaluation_results_get_version_request, - build_evaluation_results_list_latest_request, - build_evaluation_results_list_versions_request, - build_evaluation_results_start_pending_upload_request, build_evaluations_create_run_request, build_evaluations_get_request, build_evaluations_list_request, - build_indexes_create_request, build_indexes_create_version_request, build_indexes_delete_version_request, build_indexes_get_version_request, @@ -119,7 +110,7 @@ def __init__(self, *args, **kwargs) -> None: @distributed_trace_async async def get(self, name: str, **kwargs: Any) -> _models.Connection: - """Get a connection by name. + """Get a connection by name, without populating connection credentials. :param name: The name of the resource. Required. :type name: str @@ -182,21 +173,90 @@ async def get(self, name: str, **kwargs: Any) -> _models.Connection: return deserialized # type: ignore + @distributed_trace_async + async def get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, with its connection credentials. + + :param name: The name of the resource. Required. + :type name: str + :return: Connection. The Connection is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Connection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.Connection] = kwargs.pop("cls", None) + + _request = build_connections_get_with_credentials_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.Connection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + @distributed_trace def list( self, *, connection_type: Optional[Union[str, _models.ConnectionType]] = None, + default_connection: Optional[bool] = None, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any ) -> AsyncIterable["_models.Connection"]: - """List all connections in the project. + """List all connections in the project, without populating connection credentials. - :keyword connection_type: Specific type of connection to return in list. Known values are: - "AzureOpenAI", "AzureBlob", "CognitiveSearch", "CosmosDB", "ApiKey", "AppInsights", and - "CustomKeys". Default value is None. + :keyword connection_type: List connections of this specific type. Known values are: + "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", + "AppConfig", "AppInsights", and "CustomKeys". Default value is None. :paramtype connection_type: str or ~azure.ai.projects.onedp.models.ConnectionType + :keyword default_connection: List connections that are default connections. Default value is + None. + :paramtype default_connection: bool :keyword top: The number of result items to return. Default value is None. :paramtype top: int :keyword skip: The number of result items to skip. Default value is None. @@ -224,6 +284,7 @@ def prepare_request(next_link=None): _request = build_connections_list_request( connection_type=connection_type, + default_connection=default_connection, top=top, skip=skip, maxpagesize=maxpagesize, @@ -941,143 +1002,6 @@ async def delete_version(self, name: str, version: str, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - @overload - async def create( - self, name: str, body: _models.DatasetVersion, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the DatasetVersion to create. Required. - :type body: ~azure.ai.projects.onedp.models.DatasetVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the DatasetVersion to create. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the DatasetVersion to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create( - self, name: str, body: Union[_models.DatasetVersion, JSON, IO[bytes]], **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the DatasetVersion to create. Is one of the following types: - DatasetVersion, JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.DatasetVersion or JSON or IO[bytes] - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DatasetVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_datasets_create_request( - name=name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.DatasetVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - @overload async def create_version( self, @@ -1232,7 +1156,7 @@ async def start_pending_upload_version( content_type: str = "application/json", **kwargs: Any ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str @@ -1252,7 +1176,7 @@ async def start_pending_upload_version( async def start_pending_upload_version( self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str @@ -1272,7 +1196,7 @@ async def start_pending_upload_version( async def start_pending_upload_version( self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str @@ -1292,7 +1216,7 @@ async def start_pending_upload_version( async def start_pending_upload_version( self, name: str, version: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str @@ -1366,188 +1290,59 @@ async def start_pending_upload_version( return deserialized # type: ignore - @overload - async def start_pending_upload( - self, name: str, body: _models.PendingUploadRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. - :param name: The name of the resource. Required. - :type name: str - :param body: Parameters for the action. Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ +class IndexesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - @overload - async def start_pending_upload( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. + Instead, you should access the following operations through + :class:`~azure.ai.projects.onedp.aio.AIProjectClient`'s + :attr:`indexes` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list_versions( + self, + name: str, + *, + top: Optional[int] = None, + skip: Optional[str] = None, + tags: Optional[str] = None, + list_view_type: Optional[Union[str, _models.ListViewType]] = None, + **kwargs: Any + ) -> AsyncIterable["_models.Index"]: + """List all versions of the given Index. :param name: The name of the resource. Required. :type name: str - :param body: Parameters for the action. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse + :keyword top: Top count of results, top count cannot be greater than the page size. If topCount + > page size, results with be default page size count will be returned. Default value is None. + :paramtype top: int + :keyword skip: Continuation token for pagination. Default value is None. + :paramtype skip: str + :keyword tags: Comma-separated list of tag names (and optionally values). Example: + tag1,tag2=value2. Default value is None. + :paramtype tags: str + :keyword list_view_type: [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] + View type for including/excluding (for example) archived entities. Known values are: + "ActiveOnly", "ArchivedOnly", and "All". Default value is None. + :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType + :return: An iterator like instance of Index + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.onedp.models.Index] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - @overload - async def start_pending_upload( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: Parameters for the action. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def start_pending_upload( - self, name: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: Parameters for the action. Is one of the following types: PendingUploadRequest, - JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest or JSON or IO[bytes] - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PendingUploadResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_datasets_start_pending_upload_request( - name=name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.PendingUploadResponse, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.onedp.aio.AIProjectClient`'s - :attr:`indexes` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_versions( - self, - name: str, - *, - top: Optional[int] = None, - skip: Optional[str] = None, - tags: Optional[str] = None, - list_view_type: Optional[Union[str, _models.ListViewType]] = None, - **kwargs: Any - ) -> AsyncIterable["_models.Index"]: - """List all versions of the given Index. - - :param name: The name of the resource. Required. - :type name: str - :keyword top: Top count of results, top count cannot be greater than the page size. If topCount - > page size, results with be default page size count will be returned. Default value is None. - :paramtype top: int - :keyword skip: Continuation token for pagination. Default value is None. - :paramtype skip: str - :keyword tags: Comma-separated list of tag names (and optionally values). Example: - tag1,tag2=value2. Default value is None. - :paramtype tags: str - :keyword list_view_type: [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] - View type for including/excluding (for example) archived entities. Known values are: - "ActiveOnly", "ArchivedOnly", and "All". Default value is None. - :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType - :return: An iterator like instance of Index - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.onedp.models.Index] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -1843,141 +1638,6 @@ async def delete_version(self, name: str, version: str, **kwargs: Any) -> None: if cls: return cls(pipeline_response, None, {}) # type: ignore - @overload - async def create( - self, name: str, body: _models.Index, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Required. - :type body: ~azure.ai.projects.onedp.models.Index - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create(self, name: str, body: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Is one of the following types: Index, JSON, - IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.Index or JSON or IO[bytes] - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Index] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_indexes_create_request( - name=name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.Index, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - @overload async def create_version( self, name: str, version: str, body: _models.Index, *, content_type: str = "application/json", **kwargs: Any @@ -2305,821 +1965,6 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) -class EvaluationResultsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.onedp.aio.AIProjectClient`'s - :attr:`evaluation_results` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={ - "2025-05-15-preview": ["api_version", "name", "top", "skip", "tags", "list_view_type", "accept"] - }, - ) - def list_versions( - self, - name: str, - *, - top: Optional[int] = None, - skip: Optional[str] = None, - tags: Optional[str] = None, - list_view_type: Optional[Union[str, _models.ListViewType]] = None, - **kwargs: Any - ) -> AsyncIterable["_models.EvaluationResult"]: - """List all versions of the given EvaluationResult. - - :param name: The name of the resource. Required. - :type name: str - :keyword top: Top count of results, top count cannot be greater than the page size. If topCount - > page size, results with be default page size count will be returned. Default value is None. - :paramtype top: int - :keyword skip: Continuation token for pagination. Default value is None. - :paramtype skip: str - :keyword tags: Comma-separated list of tag names (and optionally values). Example: - tag1,tag2=value2. Default value is None. - :paramtype tags: str - :keyword list_view_type: [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] - View type for including/excluding (for example) archived entities. Known values are: - "ActiveOnly", "ArchivedOnly", and "All". Default value is None. - :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType - :return: An iterator like instance of EvaluationResult - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.onedp.models.EvaluationResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluationResult]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_evaluation_results_list_versions_request( - name=name, - top=top, - skip=skip, - tags=tags, - list_view_type=list_view_type, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EvaluationResult], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "top", "skip", "tags", "list_view_type", "accept"]}, - ) - def list_latest( - self, - *, - top: Optional[int] = None, - skip: Optional[str] = None, - tags: Optional[str] = None, - list_view_type: Optional[Union[str, _models.ListViewType]] = None, - **kwargs: Any - ) -> AsyncIterable["_models.EvaluationResult"]: - """List the latest version of each EvaluationResult. - - :keyword top: Top count of results, top count cannot be greater than the page size. If topCount - > page size, results with be default page size count will be returned. Default value is None. - :paramtype top: int - :keyword skip: Continuation token for pagination. Default value is None. - :paramtype skip: str - :keyword tags: Comma-separated list of tag names (and optionally values). Example: - tag1,tag2=value2. Default value is None. - :paramtype tags: str - :keyword list_view_type: [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] - View type for including/excluding (for example) archived entities. Known values are: - "ActiveOnly", "ArchivedOnly", and "All". Default value is None. - :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType - :return: An iterator like instance of EvaluationResult - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.onedp.models.EvaluationResult] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluationResult]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_evaluation_results_list_latest_request( - top=top, - skip=skip, - tags=tags, - list_view_type=list_view_type, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EvaluationResult], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "accept"]}, - ) - async def get_version(self, name: str, version: str, **kwargs: Any) -> _models.EvaluationResult: - """Get the specific version of the EvaluationResult. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to retrieve. Required. - :type version: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.EvaluationResult] = kwargs.pop("cls", None) - - _request = build_evaluation_results_get_version_request( - name=name, - version=version, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.EvaluationResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "accept"]}, - ) - async def delete_version(self, name: str, version: str, **kwargs: Any) -> None: - """Delete the specific version of the EvaluationResult. - - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the EvaluationResult to delete. Required. - :type version: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_evaluation_results_delete_version_request( - name=name, - version=version, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - async def create( - self, name: str, body: _models.EvaluationResult, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={ - "2025-05-15-preview": [ - "api_version", - "name", - "repeatability_request_id", - "repeatability_first_sent", - "client_request_id", - "content_type", - "accept", - ] - }, - ) - async def create( - self, name: str, body: Union[_models.EvaluationResult, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Is one of the following types: - EvaluationResult, JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult or JSON or IO[bytes] - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluationResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_evaluation_results_create_request( - name=name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.EvaluationResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_version( - self, - name: str, - version: str, - body: _models.EvaluationResult, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. - :type version: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_version( - self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. - :type version: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_version( - self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. - :type version: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "content_type", "accept"]}, - ) - async def create_version( - self, name: str, version: str, body: Union[_models.EvaluationResult, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. - :type version: str - :param body: The definition of the EvaluationResult to create. Is one of the following types: - EvaluationResult, JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult or JSON or IO[bytes] - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluationResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_evaluation_results_create_version_request( - name=name, - version=version, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.EvaluationResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def start_pending_upload( - self, - name: str, - version: str, - body: _models.PendingUploadRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def start_pending_upload( - self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def start_pending_upload( - self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "content_type", "accept"]}, - ) - async def start_pending_upload( - self, name: str, version: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Is one of the following types: PendingUploadRequest, - JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest or JSON or IO[bytes] - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PendingUploadResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_evaluation_results_start_pending_upload_request( - name=name, - version=version, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.PendingUploadResponse, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - class RedTeamsOperations: """ .. warning:: diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_patch.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_patch.py index 35e33cb3c9ba..28ed1195fd5e 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_patch.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/aio/operations/_patch.py @@ -9,10 +9,11 @@ """ import logging import inspect -from typing import List, Optional, Any, Tuple +from typing import List, Optional, Any, Tuple, AsyncIterable from pathlib import Path from urllib.parse import urlparse from azure.storage.blob.aio import ContainerClient +from azure.core.exceptions import ResourceNotFoundError from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.tracing.decorator import distributed_trace @@ -22,21 +23,73 @@ PendingUploadRequest, PendingUploadType, PendingUploadResponse, + Connection, + ApiKeyCredentials, + EntraIDCredentials ) -from ...models._enums import ( - DatasetType, - AuthenticationType, - ConnectionType -) +from ...models._enums import DatasetType, CredentialType, ConnectionType logger = logging.getLogger(__name__) + +class AssistantsOperations: + + # TODO: Merge all code related to handling user-agent, into a single place. + def __init__(self, outer_instance: "AIProjectClient") -> None: + + # All returned inference clients will have this application id set on their user-agent. + # For more info on user-agent HTTP header, see: + # https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy + USER_AGENT_APP_ID = "AIProjectClient" + + if hasattr(outer_instance, "_user_agent") and outer_instance._user_agent: + # If the calling application has set "user_agent" when constructing the AIProjectClient, + # take that value and prepend it to USER_AGENT_APP_ID. + self._user_agent = f"{outer_instance._user_agent}-{USER_AGENT_APP_ID}" + else: + self._user_agent = USER_AGENT_APP_ID + + self._outer_instance = outer_instance + + @distributed_trace + def get_client(self, **kwargs) -> "AssistantClient": + """Get an authenticated asynchronous AssistantClient (from the package azure-ai-assistants) to use with + your AI Foundry Project. Keyword arguments are passed to the constructor of + ChatCompletionsClient. + + .. note:: The package `azure-ai-assistants` must be installed prior to calling this method. + + :return: An authenticated Assistant Client. + :rtype: ~azure.ai.assistants.AssistantClient + + :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-assistants` package + is not installed. + :raises ~azure.core.exceptions.HttpResponseError: + """ + + try: + from azure.ai.assistants.aio import AssistantClient + except ModuleNotFoundError as e: + raise ModuleNotFoundError( + "Azure AI Assistant SDK is not installed. Please install it using 'pip install azure-ai-assistants'" + ) from e + + client = AssistantClient( + endpoint=self._outer_instance._config.endpoint, + credential=self._outer_instance._config.cedential, + user_agent=kwargs.pop("user_agent", self._user_agent), + **kwargs, + ) + + return client + + class InferenceOperations: def __init__(self, outer_instance: "AIProjectClient") -> None: # TODO: Put the user agent initialization code below in a common place used by both sync and async operations. - + # All returned inference clients will have this application id set on their user-agent. # For more info on user-agent HTTP header, see: # https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy @@ -51,7 +104,6 @@ def __init__(self, outer_instance: "AIProjectClient") -> None: self._outer_instance = outer_instance - # TODO: Use a common method for both the sync and async operations @classmethod def _get_inference_url(cls, input_url: str) -> str: @@ -67,10 +119,9 @@ def _get_inference_url(cls, input_url: str) -> str: new_url = f"https://{parsed.netloc}/api/models" return new_url - @distributed_trace def get_chat_completions_client(self, **kwargs) -> "ChatCompletionsClient": - """Get an authenticated ChatCompletionsClient (from the package azure-ai-inference) to use with + """Get an authenticated asynchronous ChatCompletionsClient (from the package azure-ai-inference) to use with AI models deployed to your AI Foundry Project. Keyword arguments are passed to the constructor of ChatCompletionsClient. @@ -93,7 +144,7 @@ def get_chat_completions_client(self, **kwargs) -> "ChatCompletionsClient": "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" ) from e - endpoint = self._get_inference_url(self._outer_instance._endpoint) + endpoint = self._get_inference_url(self._outer_instance._config.endpoint) # Older Inference SDK versions use ml.azure.com as the scope. Make sure to set the correct value here. This # is only relevent of course if EntraID auth is used. credential_scopes = ["https://cognitiveservices.azure.com/.default"] @@ -108,10 +159,9 @@ def get_chat_completions_client(self, **kwargs) -> "ChatCompletionsClient": return client - @distributed_trace def get_embeddings_client(self, **kwargs) -> "EmbeddingsClient": - """Get an authenticated EmbeddingsClient (from the package azure-ai-inference) to use with + """Get an authenticated asynchronous EmbeddingsClient (from the package azure-ai-inference) to use with AI models deployed to your AI Foundry Project. Keyword arguments are passed to the constructor of ChatCompletionsClient. @@ -134,7 +184,7 @@ def get_embeddings_client(self, **kwargs) -> "EmbeddingsClient": "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" ) from e - endpoint = self._get_inference_url(self._outer_instance._endpoint) + endpoint = self._get_inference_url(self._outer_instance._config.endpoint) # Older Inference SDK versions use ml.azure.com as the scope. Make sure to set the correct value here. This # is only relevent of course if EntraID auth is used. credential_scopes = ["https://cognitiveservices.azure.com/.default"] @@ -149,10 +199,9 @@ def get_embeddings_client(self, **kwargs) -> "EmbeddingsClient": return client - @distributed_trace def get_image_embeddings_client(self, **kwargs) -> "ImageEmbeddingsClient": - """Get an authenticated ImageEmbeddingsClient (from the package azure-ai-inference) to use with + """Get an authenticated asynchronous ImageEmbeddingsClient (from the package azure-ai-inference) to use with AI models deployed to your AI Foundry Project. Keyword arguments are passed to the constructor of ChatCompletionsClient. @@ -175,7 +224,7 @@ def get_image_embeddings_client(self, **kwargs) -> "ImageEmbeddingsClient": "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" ) from e - endpoint = self._get_inference_url(self._outer_instance._endpoint) + endpoint = self._get_inference_url(self._outer_instance._config.endpoint) # Older Inference SDK versions use ml.azure.com as the scope. Make sure to set the correct value here. This # is only relevent of course if EntraID auth is used. credential_scopes = ["https://cognitiveservices.azure.com/.default"] @@ -190,7 +239,6 @@ def get_image_embeddings_client(self, **kwargs) -> "ImageEmbeddingsClient": return client - @distributed_trace_async async def get_azure_openai_client( self, *, api_version: Optional[str] = None, connection_name: Optional[str] = None, **kwargs @@ -231,40 +279,44 @@ async def get_azure_openai_client( ) from e if connection_name: - connection = await self._outer_instance.connections.get(name=connection_name, **kwargs) + connection: Connection = await self._outer_instance.connections.get(name=connection_name, **kwargs) + if connection.type != ConnectionType.AZURE_OPEN_AI: + raise ValueError(f"Connection `{connection_name}` is not of type Azure OpenAI.") else: - connection = await self._outer_instance.connections.get_default(connection_type=ConnectionType.AZURE_OPEN_AI, **kwargs) - logger.debug("[InferenceOperations.get_azure_openai_client] connection = %s", str(connection)) + # If connection name was not specified, try to get the default Azure OpenAI connection. + connections: AsyncIterable[Connection] = self._outer_instance.connections.list( + connection_type=ConnectionType.AZURE_OPEN_AI, default_connection=True, **kwargs + ) + try: + connection: Connection = await connections.__anext__() + except StopAsyncIteration: + raise ResourceNotFoundError("No default Azure OpenAI connection found.") - azure_endpoint = ( - connection.target[:-1] - if connection.target.endswith("/") - else connection.target - ) + # TODO: if there isn't a default openai connection, we would have to by convention + # use https://{resource-name}.openai.azure.com where {resource-name} is the same as the + # foundry API endpoint (https://{resource-name}.services.ai.azure.com) - if connection.auth_type == AuthenticationType.API_KEY: + # If the connection uses API key authentication, we need to make another service call to get + # the connection with API key populated. + if connection.credentials.auth_type == CredentialType.API_KEY: + connection = await self._outer_instance.connections.get_with_credentials(name=connection_name, **kwargs) - # For api-key authentication, we need to make another service call to get the connection with credentials. - connection_with_credentials = self._outer_instance.connections.get_with_credentials(name=connection.name, **kwargs) + logger.debug("[InferenceOperations.get_azure_openai_client] connection = %s", str(connection)) - api_key: Optional[str] = None - if hasattr(connection_with_credentials.properties, "credentials"): - if hasattr(connection_with_credentials.properties.credentials, "key"): # type: ignore - api_key = connection_with_credentials.properties.credentials.key # type: ignore + azure_endpoint = connection.target[:-1] if connection.target.endswith("/") else connection.target + + if isinstance(connection.credentials, ApiKeyCredentials): logger.debug( "[InferenceOperations.get_azure_openai_client] Creating AzureOpenAI using API key authentication" ) - client = AsyncAzureOpenAI( - api_key=api_key, - azure_endpoint=azure_endpoint, - api_version=api_version - ) + api_key = connection.credentials.api_key + client = AsyncAzureOpenAI(api_key=api_key, azure_endpoint=azure_endpoint, api_version=api_version) - elif connection.auth_type == AuthenticationType.ENTRA_ID: + elif isinstance(connection.credentials, EntraIDCredentials): logger.debug( - "[InferenceOperations.get_azure_openai_client] " + "Creating AzureOpenAI using Entra ID authentication" + "[InferenceOperations.get_azure_openai_client] Creating AzureOpenAI using Entra ID authentication" ) try: @@ -289,6 +341,50 @@ async def get_azure_openai_client( return client +class TelemetryOperations: + + _connection_string: Optional[str] = None + + def __init__(self, outer_instance: "AIProjectClient") -> None: + self._outer_instance = outer_instance + + @distributed_trace + async def get_connection_string(self) -> str: + """Get the Application Insights connection string associated with the Project's Application Insights resource. + + :return: The Application Insights connection string if a the resource was enabled for the Project. + :rtype: str + :raises ~azure.core.exceptions.ResourceNotFoundError: An Application Insights connection does not + exist for this Foundry project. + """ + if not self._connection_string: + + # TODO: Two REST APIs calls can be replaced by one if we have had REST API for get_with_credentials(connection_type=ConnectionType.APPLICATION_INSIGHTS) + # Returns an empty Iterable if no connections exits. + connections: AsyncIterable[Connection] = self._outer_instance.connections.list( + connection_type=ConnectionType.APPLICATION_INSIGHTS, + default_connection=True, + ) + + connection_name: Optional[str] = None + async for connection in connections: + connection_name = connection.name + break + if not connection_name: + raise ResourceNotFoundError("No Application Insights connection found.") + + connection = await self._outer_instance.connections.get_with_credentials(name=connection_name) + + if isinstance(connection.credentials, ApiKeyCredentials): + if not connection.credentials.api_key: + raise ValueError("Application Insights connection does not have a connection string.") + self._connection_string = connection.credentials.api_key + else: + raise ValueError("Application Insights connection does not use API Key credentials.") + + return self._connection_string + + class DatasetsOperations(DatasetsOperationsGenerated): # Internal helper method to create a new dataset and return a ContainerClient from azure-storage-blob package, @@ -320,7 +416,7 @@ async def _create_dataset_and_get_its_container_client( raise ValueError("Blob reference for consumption is not present") if not pending_upload_response.blob_reference_for_consumption.credential.type: raise ValueError("Credential type is not present") - if pending_upload_response.blob_reference_for_consumption.credential.type != AuthenticationType.SAS: + if pending_upload_response.blob_reference_for_consumption.credential.type != CredentialType.SAS: raise ValueError("Credential type is not SAS") if not pending_upload_response.blob_reference_for_consumption.blob_uri: raise ValueError("Blob URI is not present or empty") @@ -356,7 +452,7 @@ async def _create_dataset_and_get_its_container_client( "[%s] pending_upload_response.blob_reference_for_consumption.credential.type = %s.", method, pending_upload_response.blob_reference_for_consumption.credential.type, - ) # == AuthenticationType.SAS + ) # == CredentialType.SAS # For overview on Blob storage SDK in Python see: # https://learn.microsoft.com/azure/storage/blobs/storage-quickstart-blobs-python @@ -370,17 +466,15 @@ async def _create_dataset_and_get_its_container_client( output_version, ) - async def upload_file_and_create( - self, *, name: str, version: Optional[str] = None, file: str, **kwargs: Any - ) -> DatasetVersion: + async def upload_file_and_create(self, *, name: str, version: str, file: str, **kwargs: Any) -> DatasetVersion: """Upload file to a blob storage, and create a dataset that references this file. This method uses the `ContainerClient.upload_blob` method from the azure-storage-blob package to upload the file. Any keyword arguments provided will be passed to the `upload_blob` method. :param name: The name of the dataset. Required. :type name: str - :param version: The version identifier for the dataset. Optional. - :type version: str or None + :param version: The version identifier for the dataset. Required. + :type version: str :param file: The file name (including optional path) to be uploaded. Required. :type file: str :return: The created dataset version. @@ -428,9 +522,7 @@ async def upload_file_and_create( return dataset_version - async def upload_folder_and_create( - self, *, name: str, version: Optional[str] = None, folder: str, **kwargs: Any - ) -> DatasetVersion: + async def upload_folder_and_create(self, *, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: """Upload all files in a folder and its sub folders to a blob storage, while maintaining relative paths, and create a dataset that references this folder. This method uses the `ContainerClient.upload_blob` method from the azure-storage-blob package @@ -438,8 +530,8 @@ async def upload_folder_and_create( :param name: The name of the dataset. Required. :type name: str - :param version: The version identifier for the dataset. Optional. - :type version: str or None + :param version: The version identifier for the dataset. Required. + :type version: str :param folder: The folder name (including optional path) to be uploaded. Required. :type file: str :return: The created dataset version. @@ -496,7 +588,9 @@ async def upload_folder_and_create( __all__: List[str] = [ "InferenceOperations", - "DatasetsOperations" + "DatasetsOperations", + "AssistantsOperations", + "TelemetryOperations", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/__init__.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/__init__.py index e64b9e16bf3f..47b84dbc259b 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/__init__.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/__init__.py @@ -14,15 +14,18 @@ from ._models import ( # type: ignore + ApiKeyCredentials, AzureAISearchIndex, + BaseCredentials, BlobReferenceForConsumption, Connection, CosmosDBIndex, + CustomCredential, DatasetVersion, Deployment, EmbeddingConfiguration, + EntraIDCredentials, Evaluation, - EvaluationResult, EvaluatorConfiguration, FileDatasetVersion, FolderDatasetVersion, @@ -31,24 +34,24 @@ InputDataset, ManagedAzureAISearchIndex, ModelDeployment, + NoAuthenticationCredentials, PendingUploadRequest, PendingUploadResponse, RedTeam, + SASCredentials, SasCredential, Sku, ) from ._enums import ( # type: ignore AttackStrategy, - AuthenticationType, ConnectionType, + CredentialType, DatasetType, DeploymentType, IndexType, ListViewType, PendingUploadType, - RepeatabilityResult, - ResultType, RiskCategory, ) from ._patch import __all__ as _patch_all @@ -56,15 +59,18 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ + "ApiKeyCredentials", "AzureAISearchIndex", + "BaseCredentials", "BlobReferenceForConsumption", "Connection", "CosmosDBIndex", + "CustomCredential", "DatasetVersion", "Deployment", "EmbeddingConfiguration", + "EntraIDCredentials", "Evaluation", - "EvaluationResult", "EvaluatorConfiguration", "FileDatasetVersion", "FolderDatasetVersion", @@ -73,21 +79,21 @@ "InputDataset", "ManagedAzureAISearchIndex", "ModelDeployment", + "NoAuthenticationCredentials", "PendingUploadRequest", "PendingUploadResponse", "RedTeam", + "SASCredentials", "SasCredential", "Sku", "AttackStrategy", - "AuthenticationType", "ConnectionType", + "CredentialType", "DatasetType", "DeploymentType", "IndexType", "ListViewType", "PendingUploadType", - "RepeatabilityResult", - "ResultType", "RiskCategory", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_enums.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_enums.py index edf3a99729e0..a81e68e9cc9d 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_enums.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_enums.py @@ -34,40 +34,44 @@ class AttackStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represents character swapping, a technique for rearranging characters in text.""" -class AuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The authentication type used by the connection.""" - - API_KEY = "ApiKey" - """API Key authentication""" - ENTRA_ID = "AAD" - """Entra ID authentication (formerly known as AAD)""" - SAS = "SAS" - """Shared Access Signature (SAS) authentication""" - CUSTOM = "CustomKeys" - """Custom authentication""" - NONE = "None" - """No authentication""" - - class ConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The Type (or category) of the connection.""" AZURE_OPEN_AI = "AzureOpenAI" """Azure OpenAI Service""" AZURE_BLOB_STORAGE = "AzureBlob" - """Azure Blob Storage""" + """Azure Blob Storage, with specified container""" + AZURE_STORAGE_ACCOUNT = "AzureStorageAccount" + """Azure Blob Storage, with container not specified (used by Assistants)""" AZURE_AI_SEARCH = "CognitiveSearch" """Azure AI Search""" COSMOS_DB = "CosmosDB" """CosmosDB""" API_KEY = "ApiKey" """Generic connection that uses API Key authentication""" + APPLICATION_CONFIGURATION = "AppConfig" + """Application Configuration""" APPLICATION_INSIGHTS = "AppInsights" """Application Insights""" CUSTOM = "CustomKeys" """Custom Keys""" +class CredentialType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The credential type used by the connection.""" + + API_KEY = "ApiKey" + """API Key credential""" + ENTRA_ID = "AAD" + """Entra ID credential (formerly known as AAD)""" + SAS = "SAS" + """Shared Access Signature (SAS) credential""" + CUSTOM = "CustomKeys" + """Custom credential""" + NONE = "None" + """No credential""" + + class DatasetType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enum to determine the type of data.""" @@ -115,32 +119,6 @@ class PendingUploadType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Temporary Blob Reference is the only supported type.""" -class RepeatabilityResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Repeatability Result header options.""" - - ACCEPTED = "accepted" - """If the request was accepted and the server guarantees that the server state reflects a single - execution of the operation.""" - REJECTED = "rejected" - """If the request was rejected because the combination of Repeatability-First-Sent and - Repeatability-Request-ID were invalid - or because the Repeatability-First-Sent value was outside the range of values held by the - server.""" - - -class ResultType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of Evaluation result.""" - - BENCHMARK = "Benchmark" - """Benchmark result""" - EVALUATION = "Evaluation" - """Evaluations Result""" - REDTEAM = "Redteam" - """Red Team Result""" - SIMULATION = "Simulation" - """Simulation Result""" - - class RiskCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Risk category for the attack objective.""" diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_models.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_models.py index e195277cfadd..8e2dbdf54f03 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_models.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/models/_models.py @@ -12,12 +12,77 @@ from .. import _model_base from .._model_base import rest_discriminator, rest_field -from ._enums import DatasetType, DeploymentType, IndexType, PendingUploadType +from ._enums import CredentialType, DatasetType, DeploymentType, IndexType, PendingUploadType if TYPE_CHECKING: from .. import models as _models +class BaseCredentials(_model_base.Model): + """A base class for connection credentials. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + EntraIDCredentials, ApiKeyCredentials, CustomCredential, NoAuthenticationCredentials, + SASCredentials + + :ivar auth_type: The type of credential used by the connection. Required. Known values are: + "ApiKey", "AAD", "SAS", "CustomKeys", and "None". + :vartype auth_type: str or ~azure.ai.projects.onedp.models.CredentialType + """ + + __mapping__: Dict[str, _model_base.Model] = {} + auth_type: str = rest_discriminator(name="authType", visibility=["read"]) + """The type of credential used by the connection. Required. Known values are: \"ApiKey\", \"AAD\", + \"SAS\", \"CustomKeys\", and \"None\".""" + + @overload + def __init__( + self, + *, + auth_type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ApiKeyCredentials(BaseCredentials, discriminator="ApiKey"): + """API Key Credential definition. + + :ivar auth_type: The credentail type. Required. API Key credential + :vartype auth_type: str or ~azure.ai.projects.onedp.models.API_KEY + :ivar api_key: API Key. + :vartype api_key: str + """ + + auth_type: Literal[CredentialType.API_KEY] = rest_discriminator(name="authType", visibility=["read"]) # type: ignore + """The credentail type. Required. API Key credential""" + api_key: Optional[str] = rest_field(name="apiKey", visibility=["read"]) + """API Key.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, auth_type=CredentialType.API_KEY, **kwargs) + + class Index(_model_base.Model): """Index resource Definition. @@ -175,35 +240,59 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class Connection(_model_base.Model): - """Response from the listSecrets operation. + """Response from the list and get connections operations. + :ivar auth_type: Discriminator property for Connection. Required. + :vartype auth_type: str :ivar name: The name of the resource. Required. :vartype name: str :ivar type: Category of the connection. Required. Known values are: "AzureOpenAI", "AzureBlob", - "CognitiveSearch", "CosmosDB", "ApiKey", "AppInsights", and "CustomKeys". + "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", "AppInsights", and + "CustomKeys". :vartype type: str or ~azure.ai.projects.onedp.models.ConnectionType :ivar target: The connection URL to be used for this service. Required. :vartype target: str - :ivar auth_type: The authentication type used by the connection. Required. Known values are: - "ApiKey", "AAD", "SAS", "CustomKeys", and "None". - :vartype auth_type: str or ~azure.ai.projects.onedp.models.AuthenticationType + :ivar is_default: Whether the connection is tagged as the default connection of its type. + Required. + :vartype is_default: bool + :ivar credentials: The credentials used by the connection. Required. + :vartype credentials: ~azure.ai.projects.onedp.models.BaseCredentials :ivar metadata: Metadata of the connection. Required. :vartype metadata: dict[str, str] """ + auth_type: str = rest_discriminator(name="authType") + """Discriminator property for Connection. Required.""" name: str = rest_field(visibility=["read"]) """The name of the resource. Required.""" type: Union[str, "_models.ConnectionType"] = rest_field(visibility=["read"]) """Category of the connection. Required. Known values are: \"AzureOpenAI\", \"AzureBlob\", - \"CognitiveSearch\", \"CosmosDB\", \"ApiKey\", \"AppInsights\", and \"CustomKeys\".""" + \"AzureStorageAccount\", \"CognitiveSearch\", \"CosmosDB\", \"ApiKey\", \"AppConfig\", + \"AppInsights\", and \"CustomKeys\".""" target: str = rest_field(visibility=["read"]) """The connection URL to be used for this service. Required.""" - auth_type: Union[str, "_models.AuthenticationType"] = rest_field(name="authType", visibility=["read"]) - """The authentication type used by the connection. Required. Known values are: \"ApiKey\", - \"AAD\", \"SAS\", \"CustomKeys\", and \"None\".""" + is_default: bool = rest_field(name="isDefault", visibility=["read"]) + """Whether the connection is tagged as the default connection of its type. Required.""" + credentials: "_models.BaseCredentials" = rest_field(visibility=["read"]) + """The credentials used by the connection. Required.""" metadata: Dict[str, str] = rest_field(visibility=["read"]) """Metadata of the connection. Required.""" + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + class CosmosDBIndex(Index, discriminator="CosmosDBNoSqlVectorStore"): """CosmosDB Vector Store Index Definition. @@ -269,6 +358,32 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, type=IndexType.COSMOS_DB, **kwargs) +class CustomCredential(BaseCredentials, discriminator="CustomKeys"): + """Custom credential defintion. + + :ivar auth_type: The credential type. Required. Custom credential + :vartype auth_type: str or ~azure.ai.projects.onedp.models.CUSTOM + """ + + auth_type: Literal[CredentialType.CUSTOM] = rest_discriminator(name="authType", visibility=["read"]) # type: ignore + """The credential type. Required. Custom credential""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, auth_type=CredentialType.CUSTOM, **kwargs) + + class DatasetVersion(_model_base.Model): """DatasetVersion Definition. @@ -415,6 +530,32 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class EntraIDCredentials(BaseCredentials, discriminator="AAD"): + """Entra ID credential definition. + + :ivar auth_type: The credential type. Required. Entra ID credential (formerly known as AAD) + :vartype auth_type: str or ~azure.ai.projects.onedp.models.ENTRA_ID + """ + + auth_type: Literal[CredentialType.ENTRA_ID] = rest_discriminator(name="authType", visibility=["read"]) # type: ignore + """The credential type. Required. Entra ID credential (formerly known as AAD)""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, auth_type=CredentialType.ENTRA_ID, **kwargs) + + class Evaluation(_model_base.Model): """Evaluation Definition. @@ -437,12 +578,6 @@ class Evaluation(_model_base.Model): :vartype properties: dict[str, str] :ivar evaluators: Evaluators to be used for the evaluation. Required. :vartype evaluators: dict[str, ~azure.ai.projects.onedp.models.EvaluatorConfiguration] - :ivar outputs: Read-only result outputs. Example: { 'evaluationResultId': - 'azureai://accounts/{AccountName}/projects/{projectName}/evaluationresults/{name}/{version}', - 'logId': - 'azureai://accounts/{AccountName}/projects/{projectName}/datasets/{dataset-name}/{dataset-version}' - }. Required. - :vartype outputs: dict[str, str] """ id: str = rest_field(visibility=["read"]) @@ -468,12 +603,6 @@ class Evaluation(_model_base.Model): visibility=["read", "create", "update", "delete", "query"] ) """Evaluators to be used for the evaluation. Required.""" - outputs: Dict[str, str] = rest_field(visibility=["read"]) - """Read-only result outputs. Example: { 'evaluationResultId': - 'azureai://accounts/{AccountName}/projects/{projectName}/evaluationresults/{name}/{version}', - 'logId': - 'azureai://accounts/{AccountName}/projects/{projectName}/datasets/{dataset-name}/{dataset-version}' - }. Required.""" @overload def __init__( @@ -498,110 +627,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class EvaluationResult(_model_base.Model): - """Evaluation Result resource Definition. - - :ivar result_type: Type of Evaluation result. Known values are: "Benchmark", "Evaluation", - "Redteam", and "Simulation". - :vartype result_type: str or ~azure.ai.projects.onedp.models.ResultType - :ivar model_name: Model Name. - :vartype model_name: str - :ivar model_version: Model Version. - :vartype model_version: str - :ivar model_asset_id: Model Asset ID. - :vartype model_asset_id: str - :ivar dataset_family: Dataset Family. - :vartype dataset_family: str - :ivar dataset_name: Dataset Name. - :vartype dataset_name: str - :ivar metrics: Metrics. - :vartype metrics: dict[str, float] - :ivar blob_uri: Blob URI. - :vartype blob_uri: str - :ivar stage: Asset stage. - :vartype stage: str - :ivar id: A unique identifier for the asset, assetId probably?. - :vartype id: str - :ivar name: The name of the resource. Required. - :vartype name: str - :ivar version: The version of the resource. Required. - :vartype version: str - :ivar description: The asset description text. - :vartype description: str - :ivar tags: Tag dictionary. Tags can be added, removed, and updated. - :vartype tags: dict[str, str] - """ - - result_type: Optional[Union[str, "_models.ResultType"]] = rest_field( - name="ResultType", visibility=["read", "create", "update", "delete", "query"] - ) - """Type of Evaluation result. Known values are: \"Benchmark\", \"Evaluation\", \"Redteam\", and - \"Simulation\".""" - model_name: Optional[str] = rest_field(name="ModelName", visibility=["read", "create", "update", "delete", "query"]) - """Model Name.""" - model_version: Optional[str] = rest_field( - name="ModelVersion", visibility=["read", "create", "update", "delete", "query"] - ) - """Model Version.""" - model_asset_id: Optional[str] = rest_field( - name="ModelAssetId", visibility=["read", "create", "update", "delete", "query"] - ) - """Model Asset ID.""" - dataset_family: Optional[str] = rest_field( - name="DatasetFamily", visibility=["read", "create", "update", "delete", "query"] - ) - """Dataset Family.""" - dataset_name: Optional[str] = rest_field( - name="DatasetName", visibility=["read", "create", "update", "delete", "query"] - ) - """Dataset Name.""" - metrics: Optional[Dict[str, float]] = rest_field( - name="Metrics", visibility=["read", "create", "update", "delete", "query"] - ) - """Metrics.""" - blob_uri: Optional[str] = rest_field(name="BlobUri", visibility=["read", "create", "update", "delete", "query"]) - """Blob URI.""" - stage: Optional[str] = rest_field(visibility=["read", "create", "update"]) - """Asset stage.""" - id: Optional[str] = rest_field(visibility=["read"]) - """A unique identifier for the asset, assetId probably?.""" - name: str = rest_field(visibility=["read"]) - """The name of the resource. Required.""" - version: str = rest_field(visibility=["read"]) - """The version of the resource. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The asset description text.""" - tags: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Tag dictionary. Tags can be added, removed, and updated.""" - - @overload - def __init__( - self, - *, - result_type: Optional[Union[str, "_models.ResultType"]] = None, - model_name: Optional[str] = None, - model_version: Optional[str] = None, - model_asset_id: Optional[str] = None, - dataset_family: Optional[str] = None, - dataset_name: Optional[str] = None, - metrics: Optional[Dict[str, float]] = None, - blob_uri: Optional[str] = None, - stage: Optional[str] = None, - description: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - class EvaluatorConfiguration(_model_base.Model): """Evaluator Configuration. @@ -914,6 +939,32 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, type=DeploymentType.MODEL_DEPLOYMENT, **kwargs) +class NoAuthenticationCredentials(BaseCredentials, discriminator="None"): + """Credentials that do not require authentication. + + :ivar auth_type: The credential type. Required. No credential + :vartype auth_type: str or ~azure.ai.projects.onedp.models.NONE + """ + + auth_type: Literal[CredentialType.NONE] = rest_discriminator(name="authType", visibility=["read"]) # type: ignore + """The credential type. Required. No credential""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, auth_type=CredentialType.NONE, **kwargs) + + class PendingUploadRequest(_model_base.Model): """Represents a request for a pending upload. @@ -1032,12 +1083,6 @@ class RedTeam(_model_base.Model): :ivar simulation_only: Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs conversation not evaluation result. Required. :vartype simulation_only: bool - :ivar outputs: Read-only result outputs. Example: { 'redTeamResultId': - 'azureai://accounts/{AccountName}/projects/{projectName}/evaluationresults/{name}/{version}', - 'logId': - 'azureai://accounts/{AccountName}/projects/{projectName}/datasets/{dataset-name}/{dataset-version}' - }. Required. - :vartype outputs: dict[str, str] :ivar risk_categories: List of risk categories to generate attack objectives for. Required. :vartype risk_categories: list[str or ~azure.ai.projects.onedp.models.RiskCategory] :ivar application_scenario: Application scenario for the red team operation, to generate @@ -1067,12 +1112,6 @@ class RedTeam(_model_base.Model): ) """Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs conversation not evaluation result. Required.""" - outputs: Dict[str, str] = rest_field(visibility=["read"]) - """Read-only result outputs. Example: { 'redTeamResultId': - 'azureai://accounts/{AccountName}/projects/{projectName}/evaluationresults/{name}/{version}', - 'logId': - 'azureai://accounts/{AccountName}/projects/{projectName}/datasets/{dataset-name}/{dataset-version}' - }. Required.""" risk_categories: List[Union[str, "_models.RiskCategory"]] = rest_field( name="riskCategories", visibility=["read", "create", "update", "delete", "query"] ) @@ -1133,6 +1172,36 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type: Literal["SAS"] = "SAS" +class SASCredentials(BaseCredentials, discriminator="SAS"): + """Shared Access Signature (SAS) credential definition. + + :ivar auth_type: The credential type. Required. Shared Access Signature (SAS) credential + :vartype auth_type: str or ~azure.ai.projects.onedp.models.SAS + :ivar sas_token: SAS token. + :vartype sas_token: str + """ + + auth_type: Literal[CredentialType.SAS] = rest_discriminator(name="authType", visibility=["read"]) # type: ignore + """The credential type. Required. Shared Access Signature (SAS) credential""" + sas_token: Optional[str] = rest_field(name="sasToken", visibility=["read"]) + """SAS token.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, auth_type=CredentialType.SAS, **kwargs) + + class Sku(_model_base.Model): """Sku information. diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/__init__.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/__init__.py index f6be99bbed9c..c8b497b4854b 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/__init__.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/__init__.py @@ -18,7 +18,6 @@ from ._operations import DatasetsOperations # type: ignore from ._operations import IndexesOperations # type: ignore from ._operations import DeploymentsOperations # type: ignore -from ._operations import EvaluationResultsOperations # type: ignore from ._operations import RedTeamsOperations # type: ignore from ._patch import __all__ as _patch_all @@ -32,7 +31,6 @@ "DatasetsOperations", "IndexesOperations", "DeploymentsOperations", - "EvaluationResultsOperations", "RedTeamsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_operations.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_operations.py index c35e8eba1e7b..effe2b7f6bbe 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_operations.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_operations.py @@ -6,13 +6,11 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import datetime from io import IOBase import json import sys from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, overload import urllib.parse -import uuid from azure.core import PipelineClient from azure.core.exceptions import ( @@ -73,9 +71,36 @@ def build_connections_get_request(name: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) +def build_connections_get_with_credentials_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/connections/{name}/withCredentials" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + def build_connections_list_request( *, connection_type: Optional[Union[str, _models.ConnectionType]] = None, + default_connection: Optional[bool] = None, top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, @@ -94,6 +119,8 @@ def build_connections_list_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if connection_type is not None: _params["connectionType"] = _SERIALIZER.query("connection_type", connection_type, "str") + if default_connection is not None: + _params["defaultConnection"] = _SERIALIZER.query("default_connection", default_connection, "bool") if top is not None: _params["top"] = _SERIALIZER.query("top", top, "int") if skip is not None: @@ -304,39 +331,6 @@ def build_datasets_delete_version_request(name: str, version: str, **kwargs: Any return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_datasets_create_request(name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datasets/{name}/versions" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if "Repeatability-Request-ID" not in _headers: - _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) - if "Repeatability-First-Sent" not in _headers: - _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( - datetime.datetime.now(datetime.timezone.utc), "rfc-1123" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - def build_datasets_create_version_request(name: str, version: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -395,35 +389,6 @@ def build_datasets_start_pending_upload_version_request( # pylint: disable=name return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_datasets_start_pending_upload_request( # pylint: disable=name-too-long - name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datasets/{name}/startPendingUpload" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - def build_indexes_list_versions_request( name: str, *, @@ -548,39 +513,6 @@ def build_indexes_delete_version_request(name: str, version: str, **kwargs: Any) return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_indexes_create_request(name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/indexes/{name}/versions" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if "Repeatability-Request-ID" not in _headers: - _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) - if "Repeatability-First-Sent" not in _headers: - _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( - datetime.datetime.now(datetime.timezone.utc), "rfc-1123" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - def build_indexes_create_version_request(name: str, version: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -670,15 +602,7 @@ def build_deployments_list_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_evaluation_results_list_versions_request( # pylint: disable=name-too-long - name: str, - *, - top: Optional[int] = None, - skip: Optional[str] = None, - tags: Optional[str] = None, - list_view_type: Optional[Union[str, _models.ListViewType]] = None, - **kwargs: Any -) -> HttpRequest: +def build_red_teams_get_request(name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -686,7 +610,7 @@ def build_evaluation_results_list_versions_request( # pylint: disable=name-too- accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluationResults/{name}/versions" + _url = "/redTeams/runs/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } @@ -695,14 +619,6 @@ def build_evaluation_results_list_versions_request( # pylint: disable=name-too- # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") - if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "str") - if tags is not None: - _params["tags"] = _SERIALIZER.query("tags", tags, "str") - if list_view_type is not None: - _params["listViewType"] = _SERIALIZER.query("list_view_type", list_view_type, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -710,13 +626,8 @@ def build_evaluation_results_list_versions_request( # pylint: disable=name-too- return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_evaluation_results_list_latest_request( # pylint: disable=name-too-long - *, - top: Optional[int] = None, - skip: Optional[str] = None, - tags: Optional[str] = None, - list_view_type: Optional[Union[str, _models.ListViewType]] = None, - **kwargs: Any +def build_red_teams_list_request( + *, top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -725,18 +636,16 @@ def build_evaluation_results_list_latest_request( # pylint: disable=name-too-lo accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluationResults" + _url = "/redTeams/runs" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if top is not None: _params["top"] = _SERIALIZER.query("top", top, "int") if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "str") - if tags is not None: - _params["tags"] = _SERIALIZER.query("tags", tags, "str") - if list_view_type is not None: - _params["listViewType"] = _SERIALIZER.query("list_view_type", list_view_type, "str") + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -744,268 +653,135 @@ def build_evaluation_results_list_latest_request( # pylint: disable=name-too-lo return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_evaluation_results_get_version_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any -) -> HttpRequest: +def build_red_teams_create_run_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluationResults/{name}/versions/{version}" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/redTeams/runs:run" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_evaluation_results_delete_version_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") +class ServicePatternsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - # Construct URL - _url = "/evaluationResults/{name}/versions/{version}" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), - } + Instead, you should access the following operations through + :class:`~azure.ai.projects.onedp.AIProjectClient`'s + :attr:`service_patterns` attribute. + """ - _url: str = _url.format(**path_format_arguments) # type: ignore + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + self.building_blocks = ServicePatternsBuildingBlocksOperations( + self._client, self._config, self._serialize, self._deserialize + ) - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) +class ConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + Instead, you should access the following operations through + :class:`~azure.ai.projects.onedp.AIProjectClient`'s + :attr:`connections` attribute. + """ -def build_evaluation_results_create_request(name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") + @distributed_trace + def get(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, without populating connection credentials. - # Construct URL - _url = "/evaluationResults/{name}/versions" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } + :param name: The name of the resource. Required. + :type name: str + :return: Connection. The Connection is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Connection + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) - _url: str = _url.format(**path_format_arguments) # type: ignore + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + cls: ClsType[_models.Connection] = kwargs.pop("cls", None) - # Construct headers - if "Repeatability-Request-ID" not in _headers: - _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) - if "Repeatability-First-Sent" not in _headers: - _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( - datetime.datetime.now(datetime.timezone.utc), "rfc-1123" + _request = build_connections_get_request( + name=name, + api_version=self._config.api_version, + headers=_headers, + params=_params, ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response -def build_evaluation_results_create_version_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluationResults/{name}/versions/{version}" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_evaluation_results_start_pending_upload_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluationResults/{name}/versions/{version}/startPendingUpload" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_red_teams_get_request(name: str, **kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/redTeams/runs/{name}" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_red_teams_list_request( - *, top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/redTeams/runs" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") - if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "int") - if maxpagesize is not None: - _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_red_teams_create_run_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/redTeams/runs:run" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -class ServicePatternsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.onedp.AIProjectClient`'s - :attr:`service_patterns` attribute. - """ - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - self.building_blocks = ServicePatternsBuildingBlocksOperations( - self._client, self._config, self._serialize, self._deserialize + response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") ) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.Connection, response.json()) -class ConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.onedp.AIProjectClient`'s - :attr:`connections` attribute. - """ + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + return deserialized # type: ignore @distributed_trace - def get(self, name: str, **kwargs: Any) -> _models.Connection: - """Get a connection by name. + def get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, with its connection credentials. :param name: The name of the resource. Required. :type name: str @@ -1026,7 +802,7 @@ def get(self, name: str, **kwargs: Any) -> _models.Connection: cls: ClsType[_models.Connection] = kwargs.pop("cls", None) - _request = build_connections_get_request( + _request = build_connections_get_with_credentials_request( name=name, api_version=self._config.api_version, headers=_headers, @@ -1073,16 +849,20 @@ def list( self, *, connection_type: Optional[Union[str, _models.ConnectionType]] = None, + default_connection: Optional[bool] = None, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any ) -> Iterable["_models.Connection"]: - """List all connections in the project. + """List all connections in the project, without populating connection credentials. - :keyword connection_type: Specific type of connection to return in list. Known values are: - "AzureOpenAI", "AzureBlob", "CognitiveSearch", "CosmosDB", "ApiKey", "AppInsights", and - "CustomKeys". Default value is None. + :keyword connection_type: List connections of this specific type. Known values are: + "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", + "AppConfig", "AppInsights", and "CustomKeys". Default value is None. :paramtype connection_type: str or ~azure.ai.projects.onedp.models.ConnectionType + :keyword default_connection: List connections that are default connections. Default value is + None. + :paramtype default_connection: bool :keyword top: The number of result items to return. Default value is None. :paramtype top: int :keyword skip: The number of result items to skip. Default value is None. @@ -1110,6 +890,7 @@ def prepare_request(next_link=None): _request = build_connections_list_request( connection_type=connection_type, + default_connection=default_connection, top=top, skip=skip, maxpagesize=maxpagesize, @@ -1828,13 +1609,21 @@ def delete_version( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore @overload - def create( - self, name: str, body: _models.DatasetVersion, *, content_type: str = "application/json", **kwargs: Any + def create_version( + self, + name: str, + version: str, + body: _models.DatasetVersion, + *, + content_type: str = "application/json", + **kwargs: Any ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. + """Create a new or replace an existing DatasetVersion with the given version id. :param name: The name of the resource. Required. :type name: str + :param version: The specific version id of the DatasetVersion to create or replace. Required. + :type version: str :param body: The definition of the DatasetVersion to create. Required. :type body: ~azure.ai.projects.onedp.models.DatasetVersion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -1846,13 +1635,15 @@ def create( """ @overload - def create( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + def create_version( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. + """Create a new or replace an existing DatasetVersion with the given version id. :param name: The name of the resource. Required. :type name: str + :param version: The specific version id of the DatasetVersion to create or replace. Required. + :type version: str :param body: The definition of the DatasetVersion to create. Required. :type body: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -1864,13 +1655,15 @@ def create( """ @overload - def create( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + def create_version( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. + """Create a new or replace an existing DatasetVersion with the given version id. :param name: The name of the resource. Required. :type name: str + :param version: The specific version id of the DatasetVersion to create or replace. Required. + :type version: str :param body: The definition of the DatasetVersion to create. Required. :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. @@ -1882,13 +1675,15 @@ def create( """ @distributed_trace - def create( - self, name: str, body: Union[_models.DatasetVersion, JSON, IO[bytes]], **kwargs: Any + def create_version( + self, name: str, version: str, body: Union[_models.DatasetVersion, JSON, IO[bytes]], **kwargs: Any ) -> _models.DatasetVersion: - """Create a new DatasetVersion. The version id will be generated by the service. + """Create a new or replace an existing DatasetVersion with the given version id. :param name: The name of the resource. Required. :type name: str + :param version: The specific version id of the DatasetVersion to create or replace. Required. + :type version: str :param body: The definition of the DatasetVersion to create. Is one of the following types: DatasetVersion, JSON, IO[bytes] Required. :type body: ~azure.ai.projects.onedp.models.DatasetVersion or JSON or IO[bytes] @@ -1917,8 +1712,9 @@ def create( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_datasets_create_request( + _request = build_datasets_create_version_request( name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -1937,7 +1733,7 @@ def create( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -1946,225 +1742,73 @@ def create( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - response_headers = {} - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - if _stream: deserialized = response.iter_bytes() else: deserialized = _deserialize(_models.DatasetVersion, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore @overload - def create_version( + def start_pending_upload_version( self, name: str, version: str, - body: _models.DatasetVersion, + body: _models.PendingUploadRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or replace an existing DatasetVersion with the given version id. + ) -> _models.PendingUploadResponse: + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the DatasetVersion to create or replace. Required. + :param version: The specific version id of the DatasetVersion to operate on. Required. :type version: str - :param body: The definition of the DatasetVersion to create. Required. - :type body: ~azure.ai.projects.onedp.models.DatasetVersion + :param body: Parameters for the action. Required. + :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion + :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_version( + def start_pending_upload_version( self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or replace an existing DatasetVersion with the given version id. + ) -> _models.PendingUploadResponse: + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the DatasetVersion to create or replace. Required. + :param version: The specific version id of the DatasetVersion to operate on. Required. :type version: str - :param body: The definition of the DatasetVersion to create. Required. + :param body: Parameters for the action. Required. :type body: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion + :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_version( + def start_pending_upload_version( self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or replace an existing DatasetVersion with the given version id. + ) -> _models.PendingUploadResponse: + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the DatasetVersion to create or replace. Required. + :param version: The specific version id of the DatasetVersion to operate on. Required. :type version: str - :param body: The definition of the DatasetVersion to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_version( - self, name: str, version: str, body: Union[_models.DatasetVersion, JSON, IO[bytes]], **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or replace an existing DatasetVersion with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to create or replace. Required. - :type version: str - :param body: The definition of the DatasetVersion to create. Is one of the following types: - DatasetVersion, JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.DatasetVersion or JSON or IO[bytes] - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.DatasetVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_datasets_create_version_request( - name=name, - version=version, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.DatasetVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def start_pending_upload_version( - self, - name: str, - version: str, - body: _models.PendingUploadRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def start_pending_upload_version( - self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def start_pending_upload_version( - self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. + :param body: Parameters for the action. Required. :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". @@ -2178,7 +1822,7 @@ def start_pending_upload_version( def start_pending_upload_version( self, name: str, version: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset for a specific version. + """Start a new or get an existing pending upload of a dataset for a specific version. :param name: The name of the resource. Required. :type name: str @@ -2186,936 +1830,11 @@ def start_pending_upload_version( :type version: str :param body: Parameters for the action. Is one of the following types: PendingUploadRequest, JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest or JSON or IO[bytes] - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PendingUploadResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_datasets_start_pending_upload_version_request( - name=name, - version=version, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.PendingUploadResponse, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def start_pending_upload( - self, name: str, body: _models.PendingUploadRequest, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: Parameters for the action. Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def start_pending_upload( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: Parameters for the action. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def start_pending_upload( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: Parameters for the action. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def start_pending_upload( - self, name: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a dataset. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: Parameters for the action. Is one of the following types: PendingUploadRequest, - JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest or JSON or IO[bytes] - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PendingUploadResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_datasets_start_pending_upload_request( - name=name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.PendingUploadResponse, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class IndexesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.onedp.AIProjectClient`'s - :attr:`indexes` attribute. - """ - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list_versions( - self, - name: str, - *, - top: Optional[int] = None, - skip: Optional[str] = None, - tags: Optional[str] = None, - list_view_type: Optional[Union[str, _models.ListViewType]] = None, - **kwargs: Any - ) -> Iterable["_models.Index"]: - """List all versions of the given Index. - - :param name: The name of the resource. Required. - :type name: str - :keyword top: Top count of results, top count cannot be greater than the page size. If topCount - > page size, results with be default page size count will be returned. Default value is None. - :paramtype top: int - :keyword skip: Continuation token for pagination. Default value is None. - :paramtype skip: str - :keyword tags: Comma-separated list of tag names (and optionally values). Example: - tag1,tag2=value2. Default value is None. - :paramtype tags: str - :keyword list_view_type: [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] - View type for including/excluding (for example) archived entities. Known values are: - "ActiveOnly", "ArchivedOnly", and "All". Default value is None. - :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType - :return: An iterator like instance of Index - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.Index] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_indexes_list_versions_request( - name=name, - top=top, - skip=skip, - tags=tags, - list_view_type=list_view_type, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Index], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def list_latest( - self, - *, - top: Optional[int] = None, - skip: Optional[str] = None, - tags: Optional[str] = None, - list_view_type: Optional[Union[str, _models.ListViewType]] = None, - **kwargs: Any - ) -> Iterable["_models.Index"]: - """List the latest version of each Index. - - :keyword top: Top count of results, top count cannot be greater than the page size. If topCount - > page size, results with be default page size count will be returned. Default value is None. - :paramtype top: int - :keyword skip: Continuation token for pagination. Default value is None. - :paramtype skip: str - :keyword tags: Comma-separated list of tag names (and optionally values). Example: - tag1,tag2=value2. Default value is None. - :paramtype tags: str - :keyword list_view_type: [ListViewType.ActiveOnly, ListViewType.ArchivedOnly, ListViewType.All] - View type for including/excluding (for example) archived entities. Known values are: - "ActiveOnly", "ArchivedOnly", and "All". Default value is None. - :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType - :return: An iterator like instance of Index - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.Index] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_indexes_list_latest_request( - top=top, - skip=skip, - tags=tags, - list_view_type=list_view_type, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Index], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_version(self, name: str, version: str, **kwargs: Any) -> _models.Index: - """Get the specific version of the Index. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to retrieve. Required. - :type version: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.Index] = kwargs.pop("cls", None) - - _request = build_indexes_get_version_request( - name=name, - version=version, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.Index, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_version( # pylint: disable=inconsistent-return-statements - self, name: str, version: str, **kwargs: Any - ) -> None: - """Delete the specific version of the Index. - - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the Index to delete. Required. - :type version: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_indexes_delete_version_request( - name=name, - version=version, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create( - self, name: str, body: _models.Index, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Required. - :type body: ~azure.ai.projects.onedp.models.Index - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create(self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create(self, name: str, body: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any) -> _models.Index: - """Create a new Index. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the Index to create. Is one of the following types: Index, JSON, - IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.Index or JSON or IO[bytes] - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Index] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_indexes_create_request( - name=name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.Index, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def create_version( - self, name: str, version: str, body: _models.Index, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new or replace an existing Index with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to create or replace. Required. - :type version: str - :param body: The definition of the Index to create. Required. - :type body: ~azure.ai.projects.onedp.models.Index - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_version( - self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new or replace an existing Index with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to create or replace. Required. - :type version: str - :param body: The definition of the Index to create. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_version( - self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Index: - """Create a new or replace an existing Index with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to create or replace. Required. - :type version: str - :param body: The definition of the Index to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_version( - self, name: str, version: str, body: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any - ) -> _models.Index: - """Create a new or replace an existing Index with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to create or replace. Required. - :type version: str - :param body: The definition of the Index to create. Is one of the following types: Index, JSON, - IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.Index or JSON or IO[bytes] - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Index] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_indexes_create_version_request( - name=name, - version=version, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.Index, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class DeploymentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.onedp.AIProjectClient`'s - :attr:`deployments` attribute. - """ - - def __init__(self, *args, **kwargs): - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def get(self, name: str, **kwargs: Any) -> _models.Deployment: - """Get a deployed model. - - :param name: Name of the deployment. Required. - :type name: str - :return: Deployment. The Deployment is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.Deployment - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) - - _request = build_deployments_get_request( - name=name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.Deployment, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, - *, - model_publisher: Optional[str] = None, - model_name: Optional[str] = None, - top: Optional[int] = None, - skip: Optional[int] = None, - **kwargs: Any - ) -> Iterable["_models.Deployment"]: - """List all deployed models in the project. - - :keyword model_publisher: Model publisher to filter models by. Default value is None. - :paramtype model_publisher: str - :keyword model_name: Model name (the publisher specific name) to filter models by. Default - value is None. - :paramtype model_name: str - :keyword top: The number of result items to return. Default value is None. - :paramtype top: int - :keyword skip: The number of result items to skip. Default value is None. - :paramtype skip: int - :return: An iterator like instance of Deployment - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.Deployment] + :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest or JSON or IO[bytes] + :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.Deployment]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -3124,81 +1843,68 @@ def list( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} - _request = build_deployments_list_request( - model_publisher=model_publisher, - model_name=model_name, - top=top, - skip=skip, - maxpagesize=maxpagesize, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PendingUploadResponse] = kwargs.pop("cls", None) - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - return _request + _request = build_datasets_start_pending_upload_version_request( + name=name, + version=version, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Deployment], deserialized.get("value", [])) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - _request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.PendingUploadResponse, response.json()) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore -class EvaluationResultsOperations: +class IndexesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.ai.projects.onedp.AIProjectClient`'s - :attr:`evaluation_results` attribute. + :attr:`indexes` attribute. """ def __init__(self, *args, **kwargs): @@ -3209,12 +1915,6 @@ def __init__(self, *args, **kwargs): self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={ - "2025-05-15-preview": ["api_version", "name", "top", "skip", "tags", "list_view_type", "accept"] - }, - ) def list_versions( self, name: str, @@ -3224,8 +1924,8 @@ def list_versions( tags: Optional[str] = None, list_view_type: Optional[Union[str, _models.ListViewType]] = None, **kwargs: Any - ) -> Iterable["_models.EvaluationResult"]: - """List all versions of the given EvaluationResult. + ) -> Iterable["_models.Index"]: + """List all versions of the given Index. :param name: The name of the resource. Required. :type name: str @@ -3241,14 +1941,14 @@ def list_versions( View type for including/excluding (for example) archived entities. Known values are: "ActiveOnly", "ArchivedOnly", and "All". Default value is None. :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType - :return: An iterator like instance of EvaluationResult - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.EvaluationResult] + :return: An iterator like instance of Index + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.Index] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.EvaluationResult]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3261,7 +1961,7 @@ def list_versions( def prepare_request(next_link=None): if not next_link: - _request = build_evaluation_results_list_versions_request( + _request = build_indexes_list_versions_request( name=name, top=top, skip=skip, @@ -3302,7 +2002,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EvaluationResult], deserialized.get("value", [])) + list_of_elem = _deserialize(List[_models.Index], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -3325,10 +2025,6 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "top", "skip", "tags", "list_view_type", "accept"]}, - ) def list_latest( self, *, @@ -3337,8 +2033,8 @@ def list_latest( tags: Optional[str] = None, list_view_type: Optional[Union[str, _models.ListViewType]] = None, **kwargs: Any - ) -> Iterable["_models.EvaluationResult"]: - """List the latest version of each EvaluationResult. + ) -> Iterable["_models.Index"]: + """List the latest version of each Index. :keyword top: Top count of results, top count cannot be greater than the page size. If topCount > page size, results with be default page size count will be returned. Default value is None. @@ -3352,14 +2048,14 @@ def list_latest( View type for including/excluding (for example) archived entities. Known values are: "ActiveOnly", "ArchivedOnly", and "All". Default value is None. :paramtype list_view_type: str or ~azure.ai.projects.onedp.models.ListViewType - :return: An iterator like instance of EvaluationResult - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.EvaluationResult] + :return: An iterator like instance of Index + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.Index] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.EvaluationResult]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3372,7 +2068,7 @@ def list_latest( def prepare_request(next_link=None): if not next_link: - _request = build_evaluation_results_list_latest_request( + _request = build_indexes_list_latest_request( top=top, skip=skip, tags=tags, @@ -3412,7 +2108,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EvaluationResult], deserialized.get("value", [])) + list_of_elem = _deserialize(List[_models.Index], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -3435,19 +2131,15 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "accept"]}, - ) - def get_version(self, name: str, version: str, **kwargs: Any) -> _models.EvaluationResult: - """Get the specific version of the EvaluationResult. + def get_version(self, name: str, version: str, **kwargs: Any) -> _models.Index: + """Get the specific version of the Index. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the EvaluationResult to retrieve. Required. + :param version: The specific version id of the Index to retrieve. Required. :type version: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3461,9 +2153,9 @@ def get_version(self, name: str, version: str, **kwargs: Any) -> _models.Evaluat _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluationResult] = kwargs.pop("cls", None) + cls: ClsType[_models.Index] = kwargs.pop("cls", None) - _request = build_evaluation_results_get_version_request( + _request = build_indexes_get_version_request( name=name, version=version, api_version=self._config.api_version, @@ -3494,7 +2186,7 @@ def get_version(self, name: str, version: str, **kwargs: Any) -> _models.Evaluat if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.EvaluationResult, response.json()) + deserialized = _deserialize(_models.Index, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3502,18 +2194,14 @@ def get_version(self, name: str, version: str, **kwargs: Any) -> _models.Evaluat return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "accept"]}, - ) def delete_version( # pylint: disable=inconsistent-return-statements self, name: str, version: str, **kwargs: Any ) -> None: - """Delete the specific version of the EvaluationResult. + """Delete the specific version of the Index. :param name: The name of the resource. Required. :type name: str - :param version: The version of the EvaluationResult to delete. Required. + :param version: The version of the Index to delete. Required. :type version: str :return: None :rtype: None @@ -3532,7 +2220,7 @@ def delete_version( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_evaluation_results_delete_version_request( + _request = build_indexes_delete_version_request( name=name, version=version, api_version=self._config.api_version, @@ -3556,244 +2244,83 @@ def delete_version( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response) if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create( - self, name: str, body: _models.EvaluationResult, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={ - "2025-05-15-preview": [ - "api_version", - "name", - "repeatability_request_id", - "repeatability_first_sent", - "client_request_id", - "content_type", - "accept", - ] - }, - ) - def create( - self, name: str, body: Union[_models.EvaluationResult, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new EvaluationResult. The version id will be generated by the service. - - :param name: The name of the resource. Required. - :type name: str - :param body: The definition of the EvaluationResult to create. Is one of the following types: - EvaluationResult, JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult or JSON or IO[bytes] - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluationResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_evaluation_results_create_request( - name=name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.EvaluationResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @overload def create_version( - self, - name: str, - version: str, - body: _models.EvaluationResult, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. + self, name: str, version: str, body: _models.Index, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Index: + """Create a new or replace an existing Index with the given version id. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. + :param version: The specific version id of the Index to create or replace. Required. :type version: str - :param body: The definition of the EvaluationResult to create. Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult + :param body: The definition of the Index to create. Required. + :type body: ~azure.ai.projects.onedp.models.Index :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create_version( self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. + ) -> _models.Index: + """Create a new or replace an existing Index with the given version id. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. + :param version: The specific version id of the Index to create or replace. Required. :type version: str - :param body: The definition of the EvaluationResult to create. Required. + :param body: The definition of the Index to create. Required. :type body: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @overload def create_version( self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. + ) -> _models.Index: + """Create a new or replace an existing Index with the given version id. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. + :param version: The specific version id of the Index to create or replace. Required. :type version: str - :param body: The definition of the EvaluationResult to create. Required. + :param body: The definition of the Index to create. Required. :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "content_type", "accept"]}, - ) def create_version( - self, name: str, version: str, body: Union[_models.EvaluationResult, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationResult: - """Create a new or replace an existing EvaluationResult with the given version id. + self, name: str, version: str, body: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Index: + """Create a new or replace an existing Index with the given version id. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the EvaluationResult to create or replace. Required. + :param version: The specific version id of the Index to create or replace. Required. :type version: str - :param body: The definition of the EvaluationResult to create. Is one of the following types: - EvaluationResult, JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.EvaluationResult or JSON or IO[bytes] - :return: EvaluationResult. The EvaluationResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.EvaluationResult + :param body: The definition of the Index to create. Is one of the following types: Index, JSON, + IO[bytes] Required. + :type body: ~azure.ai.projects.onedp.models.Index or JSON or IO[bytes] + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3808,7 +2335,7 @@ def create_version( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluationResult] = kwargs.pop("cls", None) + cls: ClsType[_models.Index] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -3817,7 +2344,7 @@ def create_version( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_evaluation_results_create_version_request( + _request = build_indexes_create_version_request( name=name, version=version, content_type=content_type, @@ -3850,98 +2377,39 @@ def create_version( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.EvaluationResult, response.json()) + deserialized = _deserialize(_models.Index, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def start_pending_upload( - self, - name: str, - version: str, - body: _models.PendingUploadRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def start_pending_upload( - self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ +class DeploymentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - @overload - def start_pending_upload( - self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. + Instead, you should access the following operations through + :class:`~azure.ai.projects.onedp.AIProjectClient`'s + :attr:`deployments` attribute. + """ - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: AIProjectClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - @api_version_validation( - method_added_on="2025-05-15-preview", - params_added_on={"2025-05-15-preview": ["api_version", "name", "version", "content_type", "accept"]}, - ) - def start_pending_upload( - self, name: str, version: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any - ) -> _models.PendingUploadResponse: - """Create or start a pending upload of a evaluation results for a specific version. + def get(self, name: str, **kwargs: Any) -> _models.Deployment: + """Get a deployed model. - :param name: The name of the resource. Required. + :param name: Name of the deployment. Required. :type name: str - :param version: The specific version id of the EvaluationResult to operate on. Required. - :type version: str - :param body: Parameters for the action. Is one of the following types: PendingUploadRequest, - JSON, IO[bytes] Required. - :type body: ~azure.ai.projects.onedp.models.PendingUploadRequest or JSON or IO[bytes] - :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.onedp.models.PendingUploadResponse + :return: Deployment. The Deployment is compatible with MutableMapping + :rtype: ~azure.ai.projects.onedp.models.Deployment :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3952,25 +2420,14 @@ def start_pending_upload( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.PendingUploadResponse] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) - _request = build_evaluation_results_start_pending_upload_request( + _request = build_deployments_get_request( name=name, - version=version, - content_type=content_type, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -3995,16 +2452,126 @@ def start_pending_upload( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) + response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.PendingUploadResponse, response.json()) + deserialized = _deserialize(_models.Deployment, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore + @distributed_trace + def list( + self, + *, + model_publisher: Optional[str] = None, + model_name: Optional[str] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + **kwargs: Any + ) -> Iterable["_models.Deployment"]: + """List all deployed models in the project. + + :keyword model_publisher: Model publisher to filter models by. Default value is None. + :paramtype model_publisher: str + :keyword model_name: Model name (the publisher specific name) to filter models by. Default + value is None. + :paramtype model_name: str + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: An iterator like instance of Deployment + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.onedp.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.Deployment]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_deployments_list_request( + model_publisher=model_publisher, + model_name=model_name, + top=top, + skip=skip, + maxpagesize=maxpagesize, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Deployment], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + class RedTeamsOperations: """ diff --git a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_patch.py b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_patch.py index f91cb0dce5f3..c13722143ffd 100644 --- a/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_patch.py +++ b/sdk/ai/azure-ai-projects-onedp/azure/ai/projects/onedp/operations/_patch.py @@ -9,31 +9,26 @@ """ import logging import inspect -from typing import List, Optional, Any, Tuple, Iterable +from typing import List, Optional, Any, Tuple, Iterable, Union from pathlib import Path from urllib.parse import urlparse from azure.storage.blob import ContainerClient from azure.core.exceptions import ResourceNotFoundError from azure.core.tracing.decorator import distributed_trace from ._operations import DatasetsOperations as DatasetsOperationsGenerated -from ..models._models import ( - DatasetVersion, - PendingUploadRequest, - PendingUploadType, - PendingUploadResponse, - Connection -) +from ..models._models import DatasetVersion, PendingUploadRequest, PendingUploadType, PendingUploadResponse, Connection, ApiKeyCredentials, EntraIDCredentials from ..models._enums import ( DatasetType, - AuthenticationType, + CredentialType, ConnectionType, ) logger = logging.getLogger(__name__) -class InferenceOperations: +class AssistantsOperations: + # TODO: Merge all code related to handling user-agent, into a single place. def __init__(self, outer_instance: "AIProjectClient") -> None: # All returned inference clients will have this application id set on their user-agent. @@ -50,6 +45,56 @@ def __init__(self, outer_instance: "AIProjectClient") -> None: self._outer_instance = outer_instance + @distributed_trace + def get_client(self, **kwargs) -> "AssistantClient": + """Get an authenticated AssistantClient (from the package azure-ai-assistants) to use with + your AI Foundry Project. Keyword arguments are passed to the constructor of + ChatCompletionsClient. + + .. note:: The package `azure-ai-assistants` must be installed prior to calling this method. + + :return: An authenticated Assistant Client. + :rtype: ~azure.ai.assistants.AssistantClient + + :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-assistants` package + is not installed. + :raises ~azure.core.exceptions.HttpResponseError: + """ + + try: + from azure.ai.assistants import AssistantClient + except ModuleNotFoundError as e: + raise ModuleNotFoundError( + "Azure AI Assistant SDK is not installed. Please install it using 'pip install azure-ai-assistants'" + ) from e + + client = AssistantClient( + endpoint=self._outer_instance._config.endpoint, + credential=self._outer_instance._config.cedential, + user_agent=kwargs.pop("user_agent", self._user_agent), + **kwargs, + ) + + return client + + +class InferenceOperations: + + def __init__(self, outer_instance: "AIProjectClient") -> None: + + # All returned inference clients will have this application id set on their user-agent. + # For more info on user-agent HTTP header, see: + # https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy + USER_AGENT_APP_ID = "AIProjectClient" + + if hasattr(outer_instance, "_user_agent") and outer_instance._user_agent: + # If the calling application has set "user_agent" when constructing the AIProjectClient, + # take that value and prepend it to USER_AGENT_APP_ID. + self._user_agent = f"{outer_instance._user_agent}-{USER_AGENT_APP_ID}" + else: + self._user_agent = USER_AGENT_APP_ID + + self._outer_instance = outer_instance @classmethod def _get_inference_url(cls, input_url: str) -> str: @@ -65,10 +110,9 @@ def _get_inference_url(cls, input_url: str) -> str: new_url = f"https://{parsed.netloc}/api/models" return new_url - @distributed_trace def get_chat_completions_client(self, **kwargs) -> "ChatCompletionsClient": - """Get an authenticated ChatCompletionsClient (from the package azure-ai-inference) to use with + """Get an authenticated ChatCompletionsClient (from the package azure-ai-inference) to use with AI models deployed to your AI Foundry Project. Keyword arguments are passed to the constructor of ChatCompletionsClient. @@ -91,7 +135,7 @@ def get_chat_completions_client(self, **kwargs) -> "ChatCompletionsClient": "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" ) from e - endpoint = self._get_inference_url(self._outer_instance._endpoint) + endpoint = self._get_inference_url(self._outer_instance._config.endpoint) # Older Inference SDK versions use ml.azure.com as the scope. Make sure to set the correct value here. This # is only relevent of course if EntraID auth is used. credential_scopes = ["https://cognitiveservices.azure.com/.default"] @@ -106,10 +150,9 @@ def get_chat_completions_client(self, **kwargs) -> "ChatCompletionsClient": return client - @distributed_trace def get_embeddings_client(self, **kwargs) -> "EmbeddingsClient": - """Get an authenticated EmbeddingsClient (from the package azure-ai-inference) to use with + """Get an authenticated EmbeddingsClient (from the package azure-ai-inference) to use with AI models deployed to your AI Foundry Project. Keyword arguments are passed to the constructor of ChatCompletionsClient. @@ -132,7 +175,7 @@ def get_embeddings_client(self, **kwargs) -> "EmbeddingsClient": "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" ) from e - endpoint = self._get_inference_url(self._outer_instance._endpoint) + endpoint = self._get_inference_url(self._outer_instance._config.endpoint) # Older Inference SDK versions use ml.azure.com as the scope. Make sure to set the correct value here. This # is only relevent of course if EntraID auth is used. credential_scopes = ["https://cognitiveservices.azure.com/.default"] @@ -147,10 +190,9 @@ def get_embeddings_client(self, **kwargs) -> "EmbeddingsClient": return client - @distributed_trace def get_image_embeddings_client(self, **kwargs) -> "ImageEmbeddingsClient": - """Get an authenticated ImageEmbeddingsClient (from the package azure-ai-inference) to use with + """Get an authenticated ImageEmbeddingsClient (from the package azure-ai-inference) to use with AI models deployed to your AI Foundry Project. Keyword arguments are passed to the constructor of ChatCompletionsClient. @@ -173,7 +215,7 @@ def get_image_embeddings_client(self, **kwargs) -> "ImageEmbeddingsClient": "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" ) from e - endpoint = self._get_inference_url(self._outer_instance._endpoint) + endpoint = self._get_inference_url(self._outer_instance._config.endpoint) # Older Inference SDK versions use ml.azure.com as the scope. Make sure to set the correct value here. This # is only relevent of course if EntraID auth is used. credential_scopes = ["https://cognitiveservices.azure.com/.default"] @@ -188,7 +230,6 @@ def get_image_embeddings_client(self, **kwargs) -> "ImageEmbeddingsClient": return client - @distributed_trace def get_azure_openai_client( self, *, api_version: Optional[str] = None, connection_name: Optional[str] = None, **kwargs @@ -229,40 +270,45 @@ def get_azure_openai_client( ) from e if connection_name: - connection = self._outer_instance.connections.get(name=connection_name, **kwargs) + connection: Connection = self._outer_instance.connections.get(name=connection_name, **kwargs) + if connection.type != ConnectionType.AZURE_OPEN_AI: + raise ValueError(f"Connection `{connection_name}` is not of type Azure OpenAI.") else: - connection = self._outer_instance.connections.get_default(connection_type=ConnectionType.AZURE_OPEN_AI, **kwargs) - logger.debug("[InferenceOperations.get_azure_openai_client] connection = %s", str(connection)) + # If connection name was not specified, try to get the default Azure OpenAI connection. + connections: Iterable[Connection] = self._outer_instance.connections.list( + connection_type=ConnectionType.AZURE_OPEN_AI, default_connection=True, **kwargs + ) + try: + connection: Connection = next(iter(connections)) + except StopAsyncIteration: + raise ResourceNotFoundError("No default Azure OpenAI connection found.") + connection_name = connection.name - azure_endpoint = ( - connection.target[:-1] - if connection.target.endswith("/") - else connection.target - ) + # TODO: if there isn't a default openai connection, we would have to by convention + # use https://{resource-name}.openai.azure.com where {resource-name} is the same as the + # foundry API endpoint (https://{resource-name}.services.ai.azure.com) - if connection.auth_type == AuthenticationType.API_KEY: + # If the connection uses API key authentication, we need to make another service call to get + # the connection with API key populated. + if connection.credentials.auth_type == CredentialType.API_KEY: + connection = self._outer_instance.connections.get_with_credentials(name=connection_name, **kwargs) - # For api-key authentication, we need to make another service call to get the connection with credentials. - connection_with_credentials = self._outer_instance.connections.get_with_credentials(name=connection.name, **kwargs) + logger.debug("[InferenceOperations.get_azure_openai_client] connection = %s", str(connection)) - api_key: Optional[str] = None - if hasattr(connection_with_credentials.properties, "credentials"): - if hasattr(connection_with_credentials.properties.credentials, "key"): # type: ignore - api_key = connection_with_credentials.properties.credentials.key # type: ignore + azure_endpoint = connection.target[:-1] if connection.target.endswith("/") else connection.target + + if isinstance(connection.credentials, ApiKeyCredentials): logger.debug( "[InferenceOperations.get_azure_openai_client] Creating AzureOpenAI using API key authentication" ) - client = AzureOpenAI( - api_key=api_key, - azure_endpoint=azure_endpoint, - api_version=api_version - ) + api_key = connection.credentials.api_key + client = AzureOpenAI(api_key=api_key, azure_endpoint=azure_endpoint, api_version=api_version) - elif connection.auth_type == AuthenticationType.ENTRA_ID: + elif isinstance(connection.credentials, EntraIDCredentials): logger.debug( - "[InferenceOperations.get_azure_openai_client] " + "Creating AzureOpenAI using Entra ID authentication" + "[InferenceOperations.get_azure_openai_client] Creating AzureOpenAI using Entra ID authentication" ) try: @@ -300,23 +346,33 @@ def get_connection_string(self) -> str: :return: The Application Insights connection string if a the resource was enabled for the Project. :rtype: str - :raises ~azure.core.exceptions.ResourceNotFoundError: An Application Insights resource was not - enabled for this project. + :raises ~azure.core.exceptions.ResourceNotFoundError: An Application Insights connection does not + exist for this Foundry project. """ if not self._connection_string: - # TODO: Test what happens here when there is no AppInsights connection. Does this throw or just returns an empty list? + # TODO: Two REST APIs calls can be replaced by one if we have had REST API for get_with_credentials(connection_type=ConnectionType.APPLICATION_INSIGHTS) + # Returns an empty Iterable if no connections exits. connections: Iterable[Connection] = self._outer_instance.connections.list( - connection_type=ConnectionType.APPLICATION_INSIGHTS + connection_type=ConnectionType.APPLICATION_INSIGHTS, + default_connection=True, ) - # Read AppInsights connection string from the first connection in the list. + connection_name: Optional[str] = None for connection in connections: - self._connection_string = connection.metadata.get("connection_string") + connection_name = connection.name break + if not connection_name: + raise ResourceNotFoundError("No Application Insights connection found.") + + connection = self._outer_instance.connections.get_with_credentials(name=connection_name) - if not self._connection_string: - raise ResourceNotFoundError("Application Insights resource was not enabled for this Project.") + if isinstance(connection.credentials, ApiKeyCredentials): + if not connection.credentials.api_key: + raise ValueError("Application Insights connection does not have a connection string.") + self._connection_string = connection.credentials.api_key + else: + raise ValueError("Application Insights connection does not use API Key credentials.") return self._connection_string @@ -352,7 +408,7 @@ def _create_dataset_and_get_its_container_client( raise ValueError("Blob reference for consumption is not present") if not pending_upload_response.blob_reference_for_consumption.credential.type: raise ValueError("Credential type is not present") - if pending_upload_response.blob_reference_for_consumption.credential.type != AuthenticationType.SAS: + if pending_upload_response.blob_reference_for_consumption.credential.type != CredentialType.SAS: raise ValueError("Credential type is not SAS") if not pending_upload_response.blob_reference_for_consumption.blob_uri: raise ValueError("Blob URI is not present or empty") @@ -388,7 +444,7 @@ def _create_dataset_and_get_its_container_client( "[%s] pending_upload_response.blob_reference_for_consumption.credential.type = %s.", method, pending_upload_response.blob_reference_for_consumption.credential.type, - ) # == AuthenticationType.SAS + ) # == CredentialType.SAS # For overview on Blob storage SDK in Python see: # https://learn.microsoft.com/azure/storage/blobs/storage-quickstart-blobs-python @@ -402,17 +458,15 @@ def _create_dataset_and_get_its_container_client( output_version, ) - def upload_file_and_create( - self, *, name: str, version: Optional[str] = None, file: str, **kwargs: Any - ) -> DatasetVersion: + def upload_file_and_create(self, *, name: str, version: str, file: str, **kwargs: Any) -> DatasetVersion: """Upload file to a blob storage, and create a dataset that references this file. This method uses the `ContainerClient.upload_blob` method from the azure-storage-blob package to upload the file. Any keyword arguments provided will be passed to the `upload_blob` method. :param name: The name of the dataset. Required. :type name: str - :param version: The version identifier for the dataset. Optional. - :type version: str or None + :param version: The version identifier for the dataset. Required. + :type version: str :param file: The file name (including optional path) to be uploaded. Required. :type file: str :return: The created dataset version. @@ -460,9 +514,7 @@ def upload_file_and_create( return dataset_version - def upload_folder_and_create( - self, *, name: str, version: Optional[str] = None, folder: str, **kwargs: Any - ) -> DatasetVersion: + def upload_folder_and_create(self, *, name: str, version: str, folder: str, **kwargs: Any) -> DatasetVersion: """Upload all files in a folder and its sub folders to a blob storage, while maintaining relative paths, and create a dataset that references this folder. This method uses the `ContainerClient.upload_blob` method from the azure-storage-blob package @@ -470,8 +522,8 @@ def upload_folder_and_create( :param name: The name of the dataset. Required. :type name: str - :param version: The version identifier for the dataset. Optional. - :type version: str or None + :param version: The version identifier for the dataset. Required. + :type version: str :param folder: The folder name (including optional path) to be uploaded. Required. :type file: str :return: The created dataset version. @@ -527,7 +579,8 @@ def upload_folder_and_create( __all__: List[str] = [ "InferenceOperations", "TelemetryOperations", - "DatasetsOperations" + "DatasetsOperations", + "AssistantsOperations", ] # Add all objects you want publicly available to users at this package level diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations.py index a3cde4337fbe..1ab1fc950f54 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations.py @@ -23,6 +23,17 @@ def test_connections_get(self, aiproject_endpoint): # please add some check logic here by yourself # ... + @AIProjectPreparer() + @recorded_by_proxy + def test_connections_get_with_credentials(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.connections.get_with_credentials( + name="str", + ) + + # please add some check logic here by yourself + # ... + @AIProjectPreparer() @recorded_by_proxy def test_connections_list(self, aiproject_endpoint): diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations_async.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations_async.py index 27f8d231a481..eada3ba467bb 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations_async.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_connections_operations_async.py @@ -24,6 +24,17 @@ async def test_connections_get(self, aiproject_endpoint): # please add some check logic here by yourself # ... + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_connections_get_with_credentials(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.connections.get_with_credentials( + name="str", + ) + + # please add some check logic here by yourself + # ... + @AIProjectPreparer() @recorded_by_proxy_async async def test_connections_list(self, aiproject_endpoint): diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations.py index 0a9241cd13bc..506b7f48ebc3 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations.py @@ -56,29 +56,6 @@ def test_datasets_delete_version(self, aiproject_endpoint): # please add some check logic here by yourself # ... - @AIProjectPreparer() - @recorded_by_proxy - def test_datasets_create(self, aiproject_endpoint): - client = self.create_client(endpoint=aiproject_endpoint) - response = client.datasets.create( - name="str", - body={ - "datasetUri": "str", - "name": "str", - "openAIPurpose": "str", - "type": "uri_file", - "version": "str", - "description": "str", - "id": "str", - "isReference": bool, - "stage": "str", - "tags": {"str": "str"}, - }, - ) - - # please add some check logic here by yourself - # ... - @AIProjectPreparer() @recorded_by_proxy def test_datasets_create_version(self, aiproject_endpoint): @@ -115,15 +92,3 @@ def test_datasets_start_pending_upload_version(self, aiproject_endpoint): # please add some check logic here by yourself # ... - - @AIProjectPreparer() - @recorded_by_proxy - def test_datasets_start_pending_upload(self, aiproject_endpoint): - client = self.create_client(endpoint=aiproject_endpoint) - response = client.datasets.start_pending_upload( - name="str", - body={"pendingUploadType": "str", "connectionName": "str", "pendingUploadId": "str"}, - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations_async.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations_async.py index a1b34b002a18..18c123286a08 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations_async.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_datasets_operations_async.py @@ -57,29 +57,6 @@ async def test_datasets_delete_version(self, aiproject_endpoint): # please add some check logic here by yourself # ... - @AIProjectPreparer() - @recorded_by_proxy_async - async def test_datasets_create(self, aiproject_endpoint): - client = self.create_async_client(endpoint=aiproject_endpoint) - response = await client.datasets.create( - name="str", - body={ - "datasetUri": "str", - "name": "str", - "openAIPurpose": "str", - "type": "uri_file", - "version": "str", - "description": "str", - "id": "str", - "isReference": bool, - "stage": "str", - "tags": {"str": "str"}, - }, - ) - - # please add some check logic here by yourself - # ... - @AIProjectPreparer() @recorded_by_proxy_async async def test_datasets_create_version(self, aiproject_endpoint): @@ -116,15 +93,3 @@ async def test_datasets_start_pending_upload_version(self, aiproject_endpoint): # please add some check logic here by yourself # ... - - @AIProjectPreparer() - @recorded_by_proxy_async - async def test_datasets_start_pending_upload(self, aiproject_endpoint): - client = self.create_async_client(endpoint=aiproject_endpoint) - response = await client.datasets.start_pending_upload( - name="str", - body={"pendingUploadType": "str", "connectionName": "str", "pendingUploadId": "str"}, - ) - - # please add some check logic here by yourself - # ... diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations.py index b689851e0c0b..2f00a1320ada 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations.py @@ -41,7 +41,6 @@ def test_evaluations_create_run(self, aiproject_endpoint): "data": "input_data", "evaluators": {"str": {"id": "str", "dataMapping": {"str": "str"}, "initParams": {"str": {}}}}, "id": "str", - "outputs": {"str": "str"}, "description": "str", "displayName": "str", "properties": {"str": "str"}, diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations_async.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations_async.py index 8f7309a47de4..e3323b6811a8 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations_async.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_evaluations_operations_async.py @@ -42,7 +42,6 @@ async def test_evaluations_create_run(self, aiproject_endpoint): "data": "input_data", "evaluators": {"str": {"id": "str", "dataMapping": {"str": "str"}, "initParams": {"str": {}}}}, "id": "str", - "outputs": {"str": "str"}, "description": "str", "displayName": "str", "properties": {"str": "str"}, diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations.py index 9a9e4dc614a8..ce533ee305e8 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations.py @@ -56,28 +56,6 @@ def test_indexes_delete_version(self, aiproject_endpoint): # please add some check logic here by yourself # ... - @AIProjectPreparer() - @recorded_by_proxy - def test_indexes_create(self, aiproject_endpoint): - client = self.create_client(endpoint=aiproject_endpoint) - response = client.indexes.create( - name="str", - body={ - "connectionName": "str", - "indexName": "str", - "name": "str", - "type": "AzureSearch", - "version": "str", - "description": "str", - "id": "str", - "stage": "str", - "tags": {"str": "str"}, - }, - ) - - # please add some check logic here by yourself - # ... - @AIProjectPreparer() @recorded_by_proxy def test_indexes_create_version(self, aiproject_endpoint): diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations_async.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations_async.py index a54e2fedb856..c2e8e93d8684 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations_async.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_indexes_operations_async.py @@ -57,28 +57,6 @@ async def test_indexes_delete_version(self, aiproject_endpoint): # please add some check logic here by yourself # ... - @AIProjectPreparer() - @recorded_by_proxy_async - async def test_indexes_create(self, aiproject_endpoint): - client = self.create_async_client(endpoint=aiproject_endpoint) - response = await client.indexes.create( - name="str", - body={ - "connectionName": "str", - "indexName": "str", - "name": "str", - "type": "AzureSearch", - "version": "str", - "description": "str", - "id": "str", - "stage": "str", - "tags": {"str": "str"}, - }, - ) - - # please add some check logic here by yourself - # ... - @AIProjectPreparer() @recorded_by_proxy_async async def test_indexes_create_version(self, aiproject_endpoint): diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations.py index 2cab66d614b0..59f381b1ce3c 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations.py @@ -41,7 +41,6 @@ def test_red_teams_create_run(self, aiproject_endpoint): "attackStrategy": ["str"], "id": "str", "numTurns": 0, - "outputs": {"str": "str"}, "riskCategories": ["str"], "scanName": "str", "simulationOnly": bool, diff --git a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations_async.py b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations_async.py index 5b7e15d68800..5af2f7fc0d1b 100644 --- a/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations_async.py +++ b/sdk/ai/azure-ai-projects-onedp/generated_tests/test_ai_project_red_teams_operations_async.py @@ -42,7 +42,6 @@ async def test_red_teams_create_run(self, aiproject_endpoint): "attackStrategy": ["str"], "id": "str", "numTurns": 0, - "outputs": {"str": "str"}, "riskCategories": ["str"], "scanName": "str", "simulationOnly": bool, diff --git a/sdk/ai/azure-ai-projects-onedp/samples/assistants/sample_get_assistant_client.py b/sdk/ai/azure-ai-projects-onedp/samples/assistants/sample_get_assistant_client.py new file mode 100644 index 000000000000..c881b1cc9757 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/assistants/sample_get_assistant_client.py @@ -0,0 +1,41 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + AssistantClient from the azure.ai.assistants package. For more information on + the azure.ai.assistants package see https://pypi.org/project/azure-ai-assistants/. + +USAGE: + python sample_get_assistant_client.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-assistants azure-identity + + Set this environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. +""" + +import os +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity import DefaultAzureCredential +from azure.ai.projects.onedp import AIProjectClient + +endpoint = os.environ["PROJECT_ENDPOINT"] + +with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, # TODO: Remove console logging +) as project_client: + + with project_client.assistants.get_client() as client: + pass diff --git a/sdk/ai/azure-ai-projects-onedp/samples/assistants/sample_get_assistant_client_async.py b/sdk/ai/azure-ai-projects-onedp/samples/assistants/sample_get_assistant_client_async.py new file mode 100644 index 000000000000..0df9d4100aab --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/assistants/sample_get_assistant_client_async.py @@ -0,0 +1,53 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + asynchronous AssistantClient from the azure.ai.assistants package. For more information on + the azure.ai.assistants package see https://pypi.org/project/azure-ai-assistants/. + +USAGE: + python sample_get_assistant_client_async.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-assistants aiohttp azure-identity + + Set this environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. +""" + +import os +import asyncio +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity import DefaultAzureCredential +from azure.ai.projects.onedp.aio import AIProjectClient + + +async def sample_get_assistant_client_async(): + + endpoint = os.environ["PROJECT_ENDPOINT"] + + async with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, # TODO: Remove console logging + ) as project_client: + + with project_client.assistants.get_client() as client: + pass + + +async def main(): + await sample_get_assistant_client_async() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections.py b/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections.py index 5e5a5133be38..33d1132d16da 100644 --- a/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections.py +++ b/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections.py @@ -25,13 +25,14 @@ import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported from azure.ai.projects.onedp import AIProjectClient from azure.ai.projects.onedp.models import ConnectionType # TODO: Remove console logging import sys import logging + logger = logging.getLogger("azure") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(stream=sys.stdout)) @@ -42,24 +43,21 @@ with AIProjectClient( endpoint=endpoint, - #credential=DefaultAzureCredential(), + # credential=DefaultAzureCredential(), credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), - logging_enable=True, # TODO: Remove console logging + logging_enable=True, # TODO: Remove console logging ) as project_client: print("List the properties of all connections:") - connections = project_client.connections.list() - for connection in connections: + for connection in project_client.connections.list(): print(connection) - + print("List the properties of all connections of a particular type (in this case, Azure OpenAI connections):") - connections = project_client.connections.list( + for connection in project_client.connections.list( connection_type=ConnectionType.AZURE_OPEN_AI, - ) - for connection in connections: + ): print(connection) print(f"Get the properties of a connection named `{connection_name}`:") connection = project_client.connections.get(connection_name) print(connection) - diff --git a/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections_async.py b/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections_async.py index 3f08e72fd0e2..321b576d7c13 100644 --- a/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections_async.py +++ b/sdk/ai/azure-ai-projects-onedp/samples/connections/sample_connections_async.py @@ -26,7 +26,7 @@ import asyncio import os from azure.identity.aio import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported from azure.ai.projects.onedp.aio import AIProjectClient from azure.ai.projects.onedp.models import ConnectionType @@ -38,7 +38,7 @@ async def sample_connections_async() -> None: async with AIProjectClient( endpoint=endpoint, - #credential=DefaultAzureCredential(), + # credential=DefaultAzureCredential(), credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), ) as project_client: diff --git a/sdk/ai/azure-ai-projects-onedp/samples/datasets/sample_datasets.py b/sdk/ai/azure-ai-projects-onedp/samples/datasets/sample_datasets.py index 3c36c0ae603c..a52eca6c8e7a 100644 --- a/sdk/ai/azure-ai-projects-onedp/samples/datasets/sample_datasets.py +++ b/sdk/ai/azure-ai-projects-onedp/samples/datasets/sample_datasets.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -24,13 +25,14 @@ import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported from azure.ai.projects.onedp import AIProjectClient from azure.ai.projects.onedp.models import DatasetVersion, ListViewType # TODO: Remove console logging import sys import logging + logger = logging.getLogger("azure") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(stream=sys.stdout)) @@ -41,12 +43,14 @@ with AIProjectClient( endpoint=endpoint, - #credential=DefaultAzureCredential(), + # credential=DefaultAzureCredential(), credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), - logging_enable=True, # TODO: Remove console logging + logging_enable=True, # TODO: Remove console logging ) as project_client: - - print("Upload a single file and create a new Dataset to reference the file. Here we explicitly specify the dataset version.") + + print( + "Upload a single file and create a new Dataset to reference the file. Here we explicitly specify the dataset version." + ) dataset: DatasetVersion = project_client.datasets.upload_file_and_create( name=dataset_name, version="1", diff --git a/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments.py b/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments.py index 48ada1e003ae..03d0412f1834 100644 --- a/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments.py +++ b/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments.py @@ -24,12 +24,13 @@ import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported from azure.ai.projects.onedp import AIProjectClient # TODO: Remove console logging import sys import logging + logger = logging.getLogger("azure") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(stream=sys.stdout)) @@ -41,9 +42,9 @@ with AIProjectClient( endpoint=endpoint, - #credential=DefaultAzureCredential(), + # credential=DefaultAzureCredential(), credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), - logging_enable=True, # TODO: Remove console logging + logging_enable=True, # TODO: Remove console logging ) as project_client: print("List all deployments:") diff --git a/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments_async.py b/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments_async.py index 1c5d7367feca..b329f0ef5aa2 100644 --- a/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments_async.py +++ b/sdk/ai/azure-ai-projects-onedp/samples/deployments/sample_deployments_async.py @@ -25,7 +25,7 @@ import asyncio import os from azure.identity.aio import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported from azure.ai.projects.onedp.aio import AIProjectClient @@ -37,7 +37,7 @@ async def sample_deployments_async() -> None: async with AIProjectClient( endpoint=endpoint, - #credential=DefaultAzureCredential(), + # credential=DefaultAzureCredential(), credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), ) as project_client: diff --git a/sdk/ai/azure-ai-projects-onedp/samples/indexes/sample_indexes.py b/sdk/ai/azure-ai-projects-onedp/samples/indexes/sample_indexes.py index 4f0e405df1d8..b7d6326ef3ae 100644 --- a/sdk/ai/azure-ai-projects-onedp/samples/indexes/sample_indexes.py +++ b/sdk/ai/azure-ai-projects-onedp/samples/indexes/sample_indexes.py @@ -25,6 +25,7 @@ # TODO: Remove console logging import sys import logging + logger = logging.getLogger("azure") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(stream=sys.stdout)) @@ -33,7 +34,7 @@ import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported from azure.ai.projects.onedp import AIProjectClient endpoint = os.environ["PROJECT_ENDPOINT"] @@ -41,9 +42,9 @@ with AIProjectClient( endpoint=endpoint, - #credential=DefaultAzureCredential(), + # credential=DefaultAzureCredential(), credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), - logging_enable=True, # TODO: Remove console logging + logging_enable=True, # TODO: Remove console logging ) as project_client: print(f"Listing all versions of the Index named `{index_name}`:") diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample1.png b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample1.png new file mode 100644 index 000000000000..59d79ff28fc5 Binary files /dev/null and b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample1.png differ diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_chat_completions_with_azure_ai_inference_client_async.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_chat_completions_with_azure_ai_inference_client_async.py new file mode 100644 index 000000000000..0bafa8d5bd85 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_chat_completions_with_azure_ai_inference_client_async.py @@ -0,0 +1,62 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + async ChatCompletionsClient from the azure.ai.inference package, and perform one + chat completions peration. For more information on the azure.ai.inference package see + https://pypi.org/project/azure-ai-inference/. + +USAGE: + python sample_chat_completions_with_azure_ai_inference_client_async.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-inference aiohttp azure-identity + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The AI model deployment name, as found in your AI Foundry project. +""" + +import os +import asyncio +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity.aio import DefaultAzureCredential +from azure.ai.projects.onedp.aio import AIProjectClient +from azure.ai.inference.models import UserMessage + + +async def sample_chat_completions_with_azure_ai_inference_client_async(): + + endpoint = os.environ["PROJECT_ENDPOINT"] + deployment_name = os.environ["DEPLOYMENT_NAME"] + + async with DefaultAzureCredential() as credential: + + async with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + ) as project_client: + + async with project_client.inference.get_chat_completions_client() as client: + + response = await client.complete( + model=deployment_name, messages=[UserMessage(content="How many feet are in a mile?")] + ) + print(response.choices[0].message.content) + + +async def main(): + await sample_chat_completions_with_azure_ai_inference_client_async() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_chat_completions_with_azure_openai_client_async.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_chat_completions_with_azure_openai_client_async.py new file mode 100644 index 000000000000..e993da88eaed --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_chat_completions_with_azure_openai_client_async.py @@ -0,0 +1,72 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + AsyncAzureOpenAI client from the openai package, and perform one chat completions + operation. + +USAGE: + python sample_chat_completions_with_azure_openai_client_async.py + + Before running the sample: + + pip install azure-ai-projects aiohttp openai + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The model deployment name, as found in your AI Foundry project. + + Update the Azure OpenAI api-version as needed (see `api_version=` below). Values can be found here: + https://learn.microsoft.com/azure/ai-services/openai/reference#api-specs +""" + +import os +import asyncio +from azure.ai.projects.onedp.aio import AIProjectClient +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity.aio import DefaultAzureCredential + + +async def sample_chat_completions_with_azure_openai_client_async(): + + endpoint = os.environ["PROJECT_ENDPOINT"] + deployment_name = os.environ["DEPLOYMENT_NAME"] + + async with DefaultAzureCredential() as credential: + + async with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, # TODO: Remove console logging + ) as project_client: + + # Get an authenticated AsyncAzureOpenAI client for your default Azure OpenAI connection: + async with await project_client.inference.get_azure_openai_client(api_version="2024-06-01") as client: + + response = await client.chat.completions.create( + model=deployment_name, + messages=[ + { + "role": "user", + "content": "How many feet are in a mile?", + }, + ], + ) + + print(response.choices[0].message.content) + + +async def main(): + await sample_chat_completions_with_azure_openai_client_async() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_image_embeddings_with_azure_ai_inference_client_async.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_image_embeddings_with_azure_ai_inference_client_async.py new file mode 100644 index 000000000000..2e236f9b2f13 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_image_embeddings_with_azure_ai_inference_client_async.py @@ -0,0 +1,70 @@ +# pylint: disable=line-too-long,useless-suppression +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + async ImageEmbeddingsClient from the azure.ai.inference package, and perform one + image embeddings operation. For more information on the azure.ai.inference package + see https://pypi.org/project/azure-ai-inference/. + +USAGE: + python sample_image_embeddings_with_azure_ai_inference_client_async.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-inference aiohttp azure-identity + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The AI model deployment name, as found in your AI Foundry project. +""" + +import os +import asyncio +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity.aio import DefaultAzureCredential +from azure.ai.projects.onedp.aio import AIProjectClient +from azure.ai.inference.models import ImageEmbeddingInput + + +async def sample_image_embeddings_with_azure_ai_inference_client_async(): + + endpoint = os.environ["PROJECT_ENDPOINT"] + deployment_name = os.environ["DEPLOYMENT_NAME"] + + async with DefaultAzureCredential() as credential: + + async with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + ) as project_client: + + async with project_client.inference.get_image_embeddings_client() as client: + + response = await client.embed( + model=deployment_name, + input=[ImageEmbeddingInput.load(image_file="sample1.png", image_format="png")], + ) + + for item in response.data: + length = len(item.embedding) + print( + f"data[{item.index}]: length={length}, [{item.embedding[0]}, {item.embedding[1]}, " + f"..., {item.embedding[length-2]}, {item.embedding[length-1]}]" + ) + + +async def main(): + await sample_image_embeddings_with_azure_ai_inference_client_async() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_text_embeddings_with_azure_ai_inference_client_async.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_text_embeddings_with_azure_ai_inference_client_async.py new file mode 100644 index 000000000000..31d327ec9f07 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/async_samples/sample_text_embeddings_with_azure_ai_inference_client_async.py @@ -0,0 +1,67 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + async EmbeddingsClient from the azure.ai.inference package, and perform one text + embeddings operation. For more information on the azure.ai.inference package see + https://pypi.org/project/azure-ai-inference/. + +USAGE: + python sample_text_embeddings_with_azure_ai_inference_client_async.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-inference aiohttp azure-identity + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The AI model deployment name, as found in your AI Foundry project. +""" + +import os +import asyncio +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity.aio import DefaultAzureCredential +from azure.ai.projects.onedp.aio import AIProjectClient + + +async def sample_text_embeddings_with_azure_ai_inference_client_async(): + + endpoint = os.environ["PROJECT_ENDPOINT"] + deployment_name = os.environ["DEPLOYMENT_NAME"] + + async with DefaultAzureCredential() as credential: + + async with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + ) as project_client: + + async with project_client.inference.get_embeddings_client() as client: + + response = await client.embed( + model=deployment_name, input=["first phrase", "second phrase", "third phrase"] + ) + + for item in response.data: + length = len(item.embedding) + print( + f"data[{item.index}]: length={length}, [{item.embedding[0]}, {item.embedding[1]}, " + f"..., {item.embedding[length-2]}, {item.embedding[length-1]}]" + ) + + +async def main(): + await sample_text_embeddings_with_azure_ai_inference_client_async() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/sample1.png b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample1.png new file mode 100644 index 000000000000..59d79ff28fc5 Binary files /dev/null and b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample1.png differ diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_chat_completions_with_azure_ai_inference_client.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_chat_completions_with_azure_ai_inference_client.py new file mode 100644 index 000000000000..b5814ec3c244 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_chat_completions_with_azure_ai_inference_client.py @@ -0,0 +1,59 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + ChatCompletionsClient from the azure.ai.inference package and perform one chat completion + operation. For more information on the azure.ai.inference package see + https://pypi.org/project/azure-ai-inference/. + +USAGE: + python sample_chat_completions_with_azure_ai_inference_client.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-inference azure-identity + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The AI model deployment name, as found in your AI Foundry project. +""" + +import os +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity import DefaultAzureCredential +from azure.ai.projects.onedp import AIProjectClient +from azure.ai.inference.models import UserMessage + +# TODO: Remove console logging +import sys +import logging + +logger = logging.getLogger("azure") +logger.setLevel(logging.DEBUG) +logger.addHandler(logging.StreamHandler(stream=sys.stdout)) +# End logging + +endpoint = os.environ["PROJECT_ENDPOINT"] +deployment_name = os.environ["DEPLOYMENT_NAME"] + +with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, # TODO: Remove console logging +) as project_client: + + with project_client.inference.get_chat_completions_client() as client: + + response = client.complete( + model=deployment_name, messages=[UserMessage(content="How many feet are in a mile?")] + ) + + print(response.choices[0].message.content) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_chat_completions_with_azure_openai_client.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_chat_completions_with_azure_openai_client.py new file mode 100644 index 000000000000..e94d78d4bcfd --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_chat_completions_with_azure_openai_client.py @@ -0,0 +1,56 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + AzureOpenAI client from the openai package, and perform one chat completion operation. + +USAGE: + python sample_chat_completions_with_azure_openai_client.py + + Before running the sample: + + pip install azure-ai-projects openai + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The model deployment name, as found in your AI Foundry project. + + Update the Azure OpenAI api-version as needed (see `api_version=` below). Values can be found here: + https://learn.microsoft.com/azure/ai-services/openai/reference#api-specs +""" + +import os +from azure.ai.projects.onedp import AIProjectClient +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity import DefaultAzureCredential + +endpoint = os.environ["PROJECT_ENDPOINT"] +deployment_name = os.environ["DEPLOYMENT_NAME"] + +with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, # TODO: Remove console logging +) as project_client: + + with project_client.inference.get_azure_openai_client(api_version="2024-06-01") as client: + + response = client.chat.completions.create( + model=deployment_name, + messages=[ + { + "role": "user", + "content": "How many feet are in a mile?", + }, + ], + ) + + print(response.choices[0].message.content) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_image_embeddings_with_azure_ai_inference_client.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_image_embeddings_with_azure_ai_inference_client.py new file mode 100644 index 000000000000..0a04d0f8ff89 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_image_embeddings_with_azure_ai_inference_client.py @@ -0,0 +1,64 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + ImageEmbeddingsClient from the azure.ai.inference package, and perform one image + embeddings operation. For more information on the azure.ai.inference package see + https://pypi.org/project/azure-ai-inference/. + +USAGE: + python sample_image_embeddings_with_azure_ai_inference_client.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-inference azure-identity + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The AI model deployment name, as found in your AI Foundry project. +""" + +import os +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity import DefaultAzureCredential +from azure.ai.projects.onedp import AIProjectClient +from azure.ai.inference.models import ImageEmbeddingInput + +# TODO: Remove console logging +import sys +import logging + +logger = logging.getLogger("azure") +logger.setLevel(logging.DEBUG) +logger.addHandler(logging.StreamHandler(stream=sys.stdout)) +# End logging + +endpoint = os.environ["PROJECT_ENDPOINT"] +deployment_name = os.environ["DEPLOYMENT_NAME"] + +with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, # TODO: Remove console logging +) as project_client: + + with project_client.inference.get_image_embeddings_client() as client: + + response = client.embed( + model=deployment_name, input=[ImageEmbeddingInput.load(image_file="sample1.png", image_format="png")] + ) + + for item in response.data: + length = len(item.embedding) + print( + f"data[{item.index}]: length={length}, [{item.embedding[0]}, {item.embedding[1]}, " + f"..., {item.embedding[length-2]}, {item.embedding[length-1]}]" + ) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_text_embeddings_with_azure_ai_inference_client.py b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_text_embeddings_with_azure_ai_inference_client.py new file mode 100644 index 000000000000..926e32d9fe97 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/inference/sample_text_embeddings_with_azure_ai_inference_client.py @@ -0,0 +1,61 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to get an authenticated + EmbeddingsClient from the azure.ai.inference package, and perform one text embeddings + operation. For more information on the azure.ai.inference package see + https://pypi.org/project/azure-ai-inference/. + +USAGE: + python sample_text_embeddings_with_azure_ai_inference_client.py + + Before running the sample: + + pip install azure-ai-projects azure-ai-inference azure-identity + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. + 2) DEPLOYMENT_NAME - The AI model deployment name, as found in your AI Foundry project. +""" + +import os +from azure.core.credentials import ( + AzureKeyCredential, +) # TODO: Remove me when EntraID is supported # TODO: Remove me when EntraID is supported +from azure.identity import DefaultAzureCredential +from azure.ai.projects.onedp import AIProjectClient + +# TODO: Remove console logging +import sys +import logging + +logger = logging.getLogger("azure") +logger.setLevel(logging.DEBUG) +logger.addHandler(logging.StreamHandler(stream=sys.stdout)) +# End logging + +endpoint = os.environ["PROJECT_ENDPOINT"] +deployment_name = os.environ["DEPLOYMENT_NAME"] + +with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, # TODO: Remove console logging +) as project_client: + + with project_client.inference.get_embeddings_client() as client: + + response = client.embed(model=deployment_name, input=["first phrase", "second phrase", "third phrase"]) + + for item in response.data: + length = len(item.embedding) + print( + f"data[{item.index}]: length={length}, [{item.embedding[0]}, {item.embedding[1]}, " + f"..., {item.embedding[length-2]}, {item.embedding[length-1]}]" + ) diff --git a/sdk/ai/azure-ai-projects-onedp/samples/telemetry/sample_telemetry.py b/sdk/ai/azure-ai-projects-onedp/samples/telemetry/sample_telemetry.py index cde9fcc9581e..e00d1b2ae38a 100644 --- a/sdk/ai/azure-ai-projects-onedp/samples/telemetry/sample_telemetry.py +++ b/sdk/ai/azure-ai-projects-onedp/samples/telemetry/sample_telemetry.py @@ -6,7 +6,8 @@ """ DESCRIPTION: Given an AIProjectClient, this sample demonstrates how to use the synchronous - `.telemtry` methods to get the Application Insights connection string. + `.telemetry` methods to get the Application Insights connection string and + enable tracing. USAGE: python sample_telemetry.py @@ -16,19 +17,20 @@ pip install azure-ai-projects azure-identity Set these environment variables with your own values: - 1) PROJECT_ENDPOINT - Required. The Azure AI Project endpoint, as found in the overview page of your + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your Azure AI Foundry project. """ import os from azure.identity import DefaultAzureCredential -from azure.core.credentials import AzureKeyCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported from azure.ai.projects.onedp import AIProjectClient from azure.ai.projects.onedp.models import ConnectionType # Start remove me -- logging import sys import logging + logger = logging.getLogger("azure") logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler(stream=sys.stdout)) @@ -38,7 +40,7 @@ with AIProjectClient( endpoint=endpoint, - #credential=DefaultAzureCredential(), + # credential=DefaultAzureCredential(), credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), logging_enable=True, ) as project_client: diff --git a/sdk/ai/azure-ai-projects-onedp/samples/telemetry/sample_telemetry_async.py b/sdk/ai/azure-ai-projects-onedp/samples/telemetry/sample_telemetry_async.py new file mode 100644 index 000000000000..f527d74bff7e --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/samples/telemetry/sample_telemetry_async.py @@ -0,0 +1,61 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +DESCRIPTION: + Given an AIProjectClient, this sample demonstrates how to use the asynchronous + `.telemetry` methods to get the Application Insights connection string and enable + tracing. + +USAGE: + python sample_telemetry_async.py + + Before running the sample: + + pip install azure-ai-projects azure-identity aiohttp + + Set these environment variables with your own values: + 1) PROJECT_ENDPOINT - The Azure AI Project endpoint, as found in the overview page of your + Azure AI Foundry project. +""" + +import os +import asyncio +from azure.identity.aio import DefaultAzureCredential +from azure.core.credentials import AzureKeyCredential # TODO: Remove me when EntraID is supported +from azure.ai.projects.onedp.aio import AIProjectClient +from azure.ai.projects.onedp.models import ConnectionType + +# Start remove me -- logging +import sys +import logging + +logger = logging.getLogger("azure") +logger.setLevel(logging.DEBUG) +logger.addHandler(logging.StreamHandler(stream=sys.stdout)) +# End remove me + +async def sample_telemetry_async() -> None: + + endpoint = os.environ["PROJECT_ENDPOINT"] + + async with AIProjectClient( + endpoint=endpoint, + # credential=DefaultAzureCredential(), + credential=AzureKeyCredential(os.environ["PROJECT_API_KEY"]), + logging_enable=True, + ) as project_client: + + print("Get the Application Insights connection string:") + connection_string = await project_client.telemetry.get_connection_string() + print(connection_string) + + +async def main(): + await sample_telemetry_async() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects-onedp/tests/README.md b/sdk/ai/azure-ai-projects-onedp/tests/README.md new file mode 100644 index 000000000000..d1cceb051bdb --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/tests/README.md @@ -0,0 +1,55 @@ +# Azure AI Project client library tests for Python + +The instructions below are for running tests locally, on a Windows machine, against the live service using a local build of the client library. + +## Build and install the client library + +- Clone or download this sample repository. +- Open a command prompt window in the folder `sdk\ai\azure-ai-projects-onedp` +- Install development dependencies: + ```bash + pip install -r dev_requirements.txt + ``` +- Install package from sources: + ```bash + pip install -e . + ``` + +## Log in to Azure + +```bash +az login +``` + +## Setup up environment variables + +Edit the file `azure_ai_projects_tests.env` located in the folder above. Follow the instructions there on how to set up Azure AI Foundry projects to be used for testing, and enter appropriate values for the environment variables used for the tests you want to run. + +## Configure test proxy + +Configure the test proxy to run live service tests without recordings: + +```bash +set AZURE_TEST_RUN_LIVE=true +set AZURE_SKIP_LIVE_RECORDING=true +set PROXY_URL=http://localhost:5000 +set AZURE_TEST_USE_CLI_AUTH=true +``` + +## Run tests + +To run all tests, type: + +```bash +pytest +``` + +To run tests in a particular folder (`tests\connections` for example): + +```bash +pytest tests\connections +``` + +## Additional information + +See [test documentation](https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/tests.md) for additional information, including how to set proxy recordings and run tests using recordings. diff --git a/sdk/ai/azure-ai-projects-onedp/tests/connections/test_connections.py b/sdk/ai/azure-ai-projects-onedp/tests/connections/test_connections.py new file mode 100644 index 000000000000..20acbef07a47 --- /dev/null +++ b/sdk/ai/azure-ai-projects-onedp/tests/connections/test_connections.py @@ -0,0 +1,9 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +class TestConnections: + + def test_connections_get(self, **kwargs): + pass diff --git a/sdk/ai/azure-ai-projects-onedp/tsp-location.yaml b/sdk/ai/azure-ai-projects-onedp/tsp-location.yaml index a07898c9f4d3..787ba4479dba 100644 --- a/sdk/ai/azure-ai-projects-onedp/tsp-location.yaml +++ b/sdk/ai/azure-ai-projects-onedp/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/ai/Azure.AI.Projects -commit: e0679682e1c4fc1ce3589ab85caad876bcfc7379 +commit: 124f9c4526d56c1da3b0a8ad59673e16178423d8 repo: Azure/azure-rest-api-specs additionalDirectories: