Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting up Python SDK for Personalizer #26296

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions eng/tox/tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ setenv =
SPHINX_APIDOC_OPTIONS=members,undoc-members,inherited-members
PIP_EXTRA_INDEX_URL=https://pypi.python.org/simple
PROXY_URL=http://localhost:5000
VIRTUALENV_WHEEL=0.37.0
VIRTUALENV_PIP=20.3.3
VIRTUALENV_SETUPTOOLS=59.6.0
VIRTUALENV_WHEEL=0.37.1
VIRTUALENV_PIP=22.2.2
VIRTUALENV_SETUPTOOLS=65.3.0
sharathmalladi marked this conversation as resolved.
Show resolved Hide resolved
deps = {[base]deps}
changedir = {toxinidir}
install_command = python -m pip install {opts} {packages} --cache-dir {toxinidir}/../.tox_pip_cache_{envname} --ignore-installed
Expand Down
30 changes: 30 additions & 0 deletions sdk/personalizer/azure-ai-personalizer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Release History

### Features Added

### Breaking Changes

### Bugs Fixed

### Other Changes

## 1.0.0b1 (2022-10-07)

Version (1.0.0b1) is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Personalizer.
This library replaces the package found here: https://pypi.org/project/azure-cognitiveservices-personalizer/

For more information about this, and preview releases of other Azure SDK libraries, please visit
https://azure.github.io/azure-sdk/releases/latest/python.html.

**Breaking changes: New API design**
sharathmalladi marked this conversation as resolved.
Show resolved Hide resolved

- New namespace/package name:
- The namespace/package name for the Form Recognizer client library has changed from
sharathmalladi marked this conversation as resolved.
Show resolved Hide resolved
`azure.cognitiveservices.personalizer` to `azure.ai.personalizer`
- Asynchronous APIs added under `azure.ai.personalizer.aio` namespace
- Authentication with API key supported using `AzureKeyCredential("<api_key>")` from `azure.core.credentials`
sharathmalladi marked this conversation as resolved.
Show resolved Hide resolved
- New underlying REST pipeline implementation based on the azure-core library
- Client and pipeline configuration is now available via keyword arguments at both the client level, and per-operation.
See README for a link to optional configuration arguments
- New error hierarchy:
- All service errors will now use the base type: `azure.core.exceptions.HttpResponseError`
21 changes: 21 additions & 0 deletions sdk/personalizer/azure-ai-personalizer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
8 changes: 8 additions & 0 deletions sdk/personalizer/azure-ai-personalizer/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
recursive-include tests *.py
include *.md
include LICENSE
include azure/__init__.py
include azure/ai/__init__.py
recursive-include samples *.py *.md
recursive-include doc *.rst
include azure/ai/personalizer/py.typed
1 change: 1 addition & 0 deletions sdk/personalizer/azure-ai-personalizer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# TBD
1 change: 1 addition & 0 deletions sdk/personalizer/azure-ai-personalizer/azure/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: str
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: str
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from ._client import PersonalizerClient
from ._version import VERSION

__version__ = VERSION

try:
from ._patch import __all__ as _patch_all
from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import
except ImportError:
_patch_all = []
from ._patch import patch_sdk as _patch_sdk

__all__ = ["PersonalizerClient"]
__all__.extend([p for p in _patch_all if p not in __all__])

_patch_sdk()
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from copy import deepcopy
from typing import Any

from azure.core import PipelineClient
from azure.core.credentials import AzureKeyCredential
from azure.core.rest import HttpRequest, HttpResponse

from ._configuration import PersonalizerClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import (
EvaluationsOperations,
EventsOperations,
FeatureImportancesOperations,
LogOperations,
ModelOperations,
MultiSlotEventsOperations,
MultiSlotOperations,
PersonalizerClientOperationsMixin,
PolicyOperations,
ServiceConfigurationOperations,
)


class PersonalizerClient(
PersonalizerClientOperationsMixin
): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes
"""Personalizer Service is an Azure Cognitive Service that makes it easy to target content and
experiences without complex pre-analysis or cleanup of past data. Given a context and
featurized content, the Personalizer Service returns which content item to show to users in
rewardActionId. As rewards are sent in response to the use of rewardActionId, the reinforcement
learning algorithm will improve the model and improve performance of future rank calls.

:ivar service_configuration: ServiceConfigurationOperations operations
:vartype service_configuration: azure.ai.personalizer.operations.ServiceConfigurationOperations
:ivar policy: PolicyOperations operations
:vartype policy: azure.ai.personalizer.operations.PolicyOperations
:ivar evaluations: EvaluationsOperations operations
:vartype evaluations: azure.ai.personalizer.operations.EvaluationsOperations
:ivar events: EventsOperations operations
:vartype events: azure.ai.personalizer.operations.EventsOperations
:ivar feature_importances: FeatureImportancesOperations operations
:vartype feature_importances: azure.ai.personalizer.operations.FeatureImportancesOperations
:ivar log: LogOperations operations
:vartype log: azure.ai.personalizer.operations.LogOperations
:ivar model: ModelOperations operations
:vartype model: azure.ai.personalizer.operations.ModelOperations
:ivar multi_slot_events: MultiSlotEventsOperations operations
:vartype multi_slot_events: azure.ai.personalizer.operations.MultiSlotEventsOperations
:ivar multi_slot: MultiSlotOperations operations
:vartype multi_slot: azure.ai.personalizer.operations.MultiSlotOperations
:param endpoint: Supported Cognitive Services endpoint. Required.
:type endpoint: str
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.AzureKeyCredential
:keyword api_version: Api Version. Default value is "2022-09-01-preview". Note that overriding
this default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None:
_endpoint = "{Endpoint}/personalizer"
self._config = PersonalizerClientConfiguration(endpoint=endpoint, credential=credential, **kwargs)
self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs)

self._serialize = Serializer()
self._deserialize = Deserializer()
self._serialize.client_side_validation = False
self.service_configuration = ServiceConfigurationOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.policy = PolicyOperations(self._client, self._config, self._serialize, self._deserialize)
self.evaluations = EvaluationsOperations(self._client, self._config, self._serialize, self._deserialize)
self.events = EventsOperations(self._client, self._config, self._serialize, self._deserialize)
self.feature_importances = FeatureImportancesOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.log = LogOperations(self._client, self._config, self._serialize, self._deserialize)
self.model = ModelOperations(self._client, self._config, self._serialize, self._deserialize)
self.multi_slot_events = MultiSlotEventsOperations(
self._client, self._config, self._serialize, self._deserialize
)
self.multi_slot = MultiSlotOperations(self._client, self._config, self._serialize, self._deserialize)

def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.

>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>

For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request

:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""

request_copy = deepcopy(request)
path_format_arguments = {
"Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
}

request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
return self._client.send_request(request_copy, **kwargs)

def close(self):
# type: () -> None
self._client.close()

def __enter__(self):
# type: () -> PersonalizerClient
self._client.__enter__()
return self

def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------

from typing import Any

from azure.core.configuration import Configuration
from azure.core.credentials import AzureKeyCredential
from azure.core.pipeline import policies

from ._version import VERSION


class PersonalizerClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes
"""Configuration for PersonalizerClient.

Note that all parameters used to create this instance are saved as instance
attributes.

:param endpoint: Supported Cognitive Services endpoint. Required.
:type endpoint: str
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.AzureKeyCredential
:keyword api_version: Api Version. Default value is "2022-09-01-preview". Note that overriding
this default value may result in unsupported behavior.
:paramtype api_version: str
"""

def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None:
super(PersonalizerClientConfiguration, self).__init__(**kwargs)
api_version = kwargs.pop("api_version", "2022-09-01-preview") # type: str

if endpoint is None:
raise ValueError("Parameter 'endpoint' must not be None.")
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")

self.endpoint = endpoint
self.credential = credential
self.api_version = api_version
kwargs.setdefault("sdk_moniker", "ai-personalizer/{}".format(VERSION))
self._configure(**kwargs)

def _configure(
self, **kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get("authentication_policy")
if self.credential and not self.authentication_policy:
self.authentication_policy = policies.AzureKeyCredentialPolicy(
self.credential, "Ocp-Apim-Subscription-Key", **kwargs
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# ------------------------------------
sharathmalladi marked this conversation as resolved.
Show resolved Hide resolved
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""Customize generated code here.
Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
from typing import List

__all__: List[str] = [] # Add all objects you want publicly available to users at this package level


def patch_sdk():
"""Do not remove from this file.
`patch_sdk` is a last resort escape hatch that allows you to do customizations
you can't accomplish using the techniques described in
https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
Loading