diff --git a/eng/tox/allowed_pylint_failures.py b/eng/tox/allowed_pylint_failures.py index 976ecf73ace6..b7a9fe1a1762 100644 --- a/eng/tox/allowed_pylint_failures.py +++ b/eng/tox/allowed_pylint_failures.py @@ -56,5 +56,6 @@ "azure-purview-catalog", "azure-messaging-nspkg", "azure-agrifood-farming", - "azure-eventhub" + "azure-eventhub", + "azure-ai-language-questionanswering" ] diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/CHANGELOG.md b/sdk/cognitivelanguage/azure-ai-language-questionanswering/CHANGELOG.md new file mode 100644 index 000000000000..204bcaba541c --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/CHANGELOG.md @@ -0,0 +1,6 @@ +# Release History + +## 1.0.0b1 (unreleased) + +### Features Added +* Initial release. diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/MANIFEST.in b/sdk/cognitivelanguage/azure-ai-language-questionanswering/MANIFEST.in new file mode 100644 index 000000000000..b0148148eaf2 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/MANIFEST.in @@ -0,0 +1,8 @@ +include _meta.json +include *.md +include azure/__init__.py +include azure/ai/__init__.py +include azure/ai/language/__init__.py +recursive-include tests *.py +recursive-include samples *.py *.md +include azure/ai/language/questionanswering/py.typed diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/README.md b/sdk/cognitivelanguage/azure-ai-language-questionanswering/README.md new file mode 100644 index 000000000000..4e2634d38137 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/README.md @@ -0,0 +1,212 @@ +[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/azure-sdk-for-python.client?branchName=main)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=46?branchName=main) + +# Azure Cognitive Language Services Question Answering client library for Python + +Question Answering is a cloud-based API service that lets you create a conversational question-and-answer layer over your existing data. Use it to build a knowledge base by extracting questions and answers from your semi-structured content, including FAQ, manuals, and documents. Answer users’ questions with the best answers from the QnAs in your knowledge base—automatically. Your knowledge base gets smarter, too, as it continually learns from users' behavior. + +[Source code][questionanswering_client_src] | [Package (PyPI)][questionanswering_pypi_package] | [API reference documentation][questionanswering_refdocs] | [Product documentation][questionanswering_docs] | [Samples][questionanswering_samples] + +## Getting started + +### Prerequisites + +* Python 2.7, or 3.6 or later is required to use this package. +* An [Azure subscription][azure_subscription] +* An existing Question Answering resource + +> Note: the new unified Cognitive Language Services are not currently available for deployment. + +### Install the package + +Install the Azure QuestionAnswering client library for Python with [pip][pip_link]: + +```bash +pip install azure-ai-language-questionanswering +``` + +### Authenticate the client + +In order to interact with the Question Answering service, you'll need to create an instance of the [`QuestionAnsweringClient`][questionanswering_client_class] class. You will need an **endpoint**, and an **API key** instantiate a client object. For more information regarding authenticating with Cognitive Services, see [Authenticate requests to Azure Cognitive Services][cognitive_auth]. + +#### Get an API key + +You can get the **endpoint** and an **API key** from the Cognitive Services resource or Question Answering resource in the [Azure Portal][azure_portal]. + +Alternatively, use the [Azure CLI][azure_cli] command shown below to get the API key from the Question Answering resource. + +```powershell +az cognitiveservices account keys list --resource-group --name +``` + +#### Create QuestionAnsweringClient + +Once you've determined your **endpoint** and **API key** you can instantiate a `QuestionAnsweringClient`: + +```python +from azure.core.credentials import AzureKeyCredential +from azure.ai.language.questionanswering import QuestionAnsweringClient + +endpoint = "https://{myaccount}.api.cognitive.microsoft.com" +credential = AzureKeyCredential("{api-key}") + +client = QuestionAnsweringClient(endpoint, credential) +``` + +## Key concepts + +### QuestionAnsweringClient + +The [`QuestionAnsweringClient`][questionanswering_client_class] is the primary interface for asking questions using a knowledge base with your own information, or text input using pre-trained models. +For asynchronous operations, an async `QuestionAnsweringClient` is in the `azure.ai.language.questionanswering.aio` namespace. + +## Examples + +The `azure-ai-language-questionanswering` client library provides both synchronous and asynchronous APIs. + +The following examples show common scenarios using the `client` [created above](#create-questionansweringclient). +- [Ask a question](#ask-a-question) +- [Ask a follow-up question](#ask-a-follow-up-question) +- [Asynchronous operations](#asynchronous-operations) + +### Ask a question + +The only input required to ask a question using a knowledgebase is just the question itself: + +```python +from azure.ai.language.questionanswering import models as qna + +params = qna.KnowledgebaseQueryParameters( + question="How long should my Surface battery last?" +) + +output = client.query_knowledgebase( + project_name="FAQ", + knowledgebase_query_parameters=params +) +for candidate in output.answers: + print("({}) {}".format(candidate.confidence_score, candidate.answer)) + print("Source: {}".format(candidate.source)) + +``` + +You can set additional properties on `KnowledgebaseQueryParameters` to limit the number of answers, specify a minimum confidence score, and more. + +### Ask a follow-up question + +If your knowledgebase is configured for [chit-chat][questionanswering_docs_chat], you can ask a follow-up question provided the previous question-answering ID and, optionally, the exact question the user asked: + +```python +params = qna.models.KnowledgebaseQueryParameters( + question="How long should charging take?" + context=qna.models.KnowledgebaseAnswerRequestContext( + previous_user_query="How long should my Surface battery last?", + previous_qna_id=previous_answer.id + ) +) + +output = client.query_knowledgebase( + project_name="FAQ", + knowledgebase_query_parameters=params +) +for candidate in output.answers: + print("({}) {}".format(candidate.confidence_score, candidate.answer)) + print("Source: {}".format(candidate.source)) + +``` +### Asynchronous operations + +The above examples can also be run asynchronously using the client in the `aio` namespace: +```python +from azure.core.credentials import AzureKeyCredential +from azure.ai.language.questionanswering.aio import QuestionAnsweringClient +from azure.ai.language.questionanswering import models as qna + +client = QuestionAnsweringClient(endpoint, credential) + +params = qna.KnowledgebaseQueryParameters( + question="How long should my Surface battery last?" +) + +output = await client.query_knowledgebase( + project_name="FAQ", + knowledgebase_query_parameters=params +) +``` + +## Optional Configuration +Optional keyword arguments can be passed in at the client and per-operation level. The azure-core [reference documentation][azure_core_ref_docs] describes available configurations for retries, logging, transport protocols, and more. + +## Troubleshooting + +### General +Azure QuestionAnswering clients raise exceptions defined in [Azure Core][azure_core_readme]. +When you interact with the Cognitive Language Services Question Answering client library using the .Python SDK, errors returned by the service correspond to the same HTTP status codes returned for [REST API][questionanswering_rest_docs] requests. + +For example, if you submit a question to a non-existant knowledge base, a `400` error is returned indicating "Bad Request". + +```python +from azure.core.exceptions import HttpResponseError + +try: + client.query_knowledgebase( + project_name="invalid-knowledgebase", + knowledgebase_query_parameters=params + ) +except HttpResponseError as error: + print("Query failed: {}".format(error.message)) +``` + +### Logging +This library uses the standard +[logging][python_logging] library for logging. +Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO +level. + +Detailed DEBUG level logging, including request/response bodies and unredacted +headers, can be enabled on a client with the `logging_enable` argument. + +See full SDK logging documentation with examples [here][sdk_logging_docs]. + +## Next steps + +* View our [samples][questionanswering_samples]. +* Read about the different [features][questionanswering_docs_features] of the Question Answering service. +* Try our service [demos][questionanswering_docs_demos]. + +## Contributing + +See the [CONTRIBUTING.md][contributing] for details on building, testing, and contributing to this library. + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla]. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. + + +[azure_cli]: https://docs.microsoft.com/cli/azure/ +[azure_portal]: https://portal.azure.com/ +[azure_subscription]: https://azure.microsoft.com/free/ +[cla]: https://cla.microsoft.com +[coc_contact]: mailto:opencode@microsoft.com +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ +[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/ +[cognitive_auth]: https://docs.microsoft.com/azure/cognitive-services/authentication/ +[contributing]: https://github.com/Azure/azure-sdk-for-python/blob/main/CONTRIBUTING.md +[python_logging]: https://docs.python.org/3/library/logging.html +[sdk_logging_docs]: https://docs.microsoft.com/azure/developer/python/azure-sdk-logging +[azure_core_ref_docs]: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-core/latest/azure.core.html +[azure_core_readme]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md +[pip_link]:https://pypi.org/project/pip/ +[questionanswering_client_class]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_question_answering_client.py#L27 +[questionanswering_client_src]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/ +[questionanswering_docs]: https://azure.microsoft.com/services/cognitive-services/qna-maker/ +[questionanswering_docs_chat]: https://docs.microsoft.com/azure/cognitive-services/qnamaker/how-to/chit-chat-knowledge-base +[questionanswering_docs_demos]: https://azure.microsoft.com/services/cognitive-services/qna-maker/#demo +[questionanswering_docs_features]: https://azure.microsoft.com/services/cognitive-services/qna-maker/#features +[questionanswering_pypi_package]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/ +[questionanswering_refdocs]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/ +[questionanswering_rest_docs]: https://docs.microsoft.com/rest/api/cognitiveservices-qnamaker/ +[questionanswering_samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/README.md + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Ftemplate%2Fazure-template%2FREADME.png) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/__init__.py new file mode 100644 index 000000000000..69e3be50dac4 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/__init__.py new file mode 100644 index 000000000000..69e3be50dac4 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/__init__.py new file mode 100644 index 000000000000..69e3be50dac4 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/__init__.py new file mode 100644 index 000000000000..d1224fabb06b --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/__init__.py @@ -0,0 +1,19 @@ +# 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 ._question_answering_client import QuestionAnsweringClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['QuestionAnsweringClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_configuration.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_configuration.py new file mode 100644 index 000000000000..f6230facf092 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_configuration.py @@ -0,0 +1,70 @@ +# 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 TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import AzureKeyCredential + + +class QuestionAnsweringClientConfiguration(Configuration): + """Configuration for QuestionAnsweringClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.AzureKeyCredential + :param endpoint: Supported Cognitive Services endpoint (e.g., https://:code:``.api.cognitiveservices.azure.com). + :type endpoint: str + """ + + def __init__( + self, + credential, # type: AzureKeyCredential + endpoint, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + super(QuestionAnsweringClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.endpoint = endpoint + self.api_version = "2021-05-01-preview" + kwargs.setdefault("sdk_moniker", "ai-language-questionanswering/{}".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 + ) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_question_answering_client.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_question_answering_client.py new file mode 100644 index 000000000000..65bc45457fd3 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_question_answering_client.py @@ -0,0 +1,94 @@ +# 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 TYPE_CHECKING + +from azure.core import PipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import AzureKeyCredential + from azure.core.rest import HttpRequest, HttpResponse + +from ._configuration import QuestionAnsweringClientConfiguration +from .operations import QuestionAnsweringClientOperationsMixin +from . import models + + +class QuestionAnsweringClient(QuestionAnsweringClientOperationsMixin): + """The language service API is a suite of natural language processing (NLP) skills built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction, language detection and question answering. Further documentation can be found in :code:`https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview`. + + :param endpoint: Supported Cognitive Services endpoint (e.g., https://:code:``.api.cognitiveservices.azure.com). + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.AzureKeyCredential + """ + + def __init__( + self, + endpoint, # type: str + credential, # type: AzureKeyCredential + **kwargs # type: Any + ): + # type: (...) -> None + base_url = "{Endpoint}/language" + self._config = QuestionAnsweringClientConfiguration(credential, endpoint, **kwargs) + self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + + def send_request(self, request, **kwargs): + # type: (HttpRequest, Any) -> HttpResponse + """Runs the network request through the client's chained policies. + + We have helper methods to create requests specific to this service in `azure.ai.language.questionanswering.rest`. + Use these helper methods to create the request you pass to this method. See our example below: + + >>> from azure.ai.language.questionanswering.rest import build_query_knowledgebase_request + >>> request = build_query_knowledgebase_request(project_name, json, content, deployment_name) + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + For advanced cases, you can also create your own :class:`~azure.core.rest.HttpRequest` + and pass it in. + + :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: () -> QuestionAnsweringClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_version.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_version.py new file mode 100644 index 000000000000..e5754a47ce68 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/_version.py @@ -0,0 +1,9 @@ +# 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. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0b1" diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/__init__.py new file mode 100644 index 000000000000..3a05f81f6173 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/__init__.py @@ -0,0 +1,11 @@ +# 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 ._question_answering_client import QuestionAnsweringClient + +__all__ = ['QuestionAnsweringClient'] diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/_configuration.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/_configuration.py new file mode 100644 index 000000000000..b682db120b9a --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/_configuration.py @@ -0,0 +1,56 @@ +# 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 QuestionAnsweringClientConfiguration(Configuration): + """Configuration for QuestionAnsweringClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.AzureKeyCredential + :param endpoint: Supported Cognitive Services endpoint (e.g., https://:code:``.api.cognitiveservices.azure.com). + :type endpoint: str + """ + + def __init__(self, credential: AzureKeyCredential, endpoint: str, **kwargs: Any) -> None: + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + super(QuestionAnsweringClientConfiguration, self).__init__(**kwargs) + + self.credential = credential + self.endpoint = endpoint + self.api_version = "2021-05-01-preview" + kwargs.setdefault("sdk_moniker", "ai-language-questionanswering/{}".format(VERSION)) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> 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.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**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 + ) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/_question_answering_client.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/_question_answering_client.py new file mode 100644 index 000000000000..399cc33816b7 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/_question_answering_client.py @@ -0,0 +1,79 @@ +# 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 AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential +from azure.core.rest import AsyncHttpResponse, HttpRequest +from msrest import Deserializer, Serializer + +from ._configuration import QuestionAnsweringClientConfiguration +from .operations import QuestionAnsweringClientOperationsMixin +from .. import models + + +class QuestionAnsweringClient(QuestionAnsweringClientOperationsMixin): + """The language service API is a suite of natural language processing (NLP) skills built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction, language detection and question answering. Further documentation can be found in :code:`https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview`. + + :param endpoint: Supported Cognitive Services endpoint (e.g., https://:code:``.api.cognitiveservices.azure.com). + :type endpoint: str + :param credential: Credential needed for the client to connect to Azure. + :type credential: ~azure.core.credentials.AzureKeyCredential + """ + + def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: + base_url = "{Endpoint}/language" + self._config = QuestionAnsweringClientConfiguration(credential, endpoint, **kwargs) + self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + + def send_request(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + """Runs the network request through the client's chained policies. + + We have helper methods to create requests specific to this service in `azure.ai.language.questionanswering.rest`. + Use these helper methods to create the request you pass to this method. See our example below: + + >>> from azure.ai.language.questionanswering.rest import build_query_knowledgebase_request + >>> request = build_query_knowledgebase_request(project_name, json, content, deployment_name) + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + For advanced cases, you can also create your own :class:`~azure.core.rest.HttpRequest` + and pass it in. + + :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.AsyncHttpResponse + """ + 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) + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "QuestionAnsweringClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/operations/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/operations/__init__.py new file mode 100644 index 000000000000..200be9f1c22e --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/operations/__init__.py @@ -0,0 +1,13 @@ +# 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 ._question_answering_client_operations import QuestionAnsweringClientOperationsMixin + +__all__ = [ + "QuestionAnsweringClientOperationsMixin", +] diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/operations/_question_answering_client_operations.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/operations/_question_answering_client_operations.py new file mode 100644 index 000000000000..1c808e40ea9f --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/aio/operations/_question_answering_client_operations.py @@ -0,0 +1,141 @@ +# 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. +# -------------------------------------------------------------------------- +import functools +from typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest + +from ... import models as _models, rest + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + + +class QuestionAnsweringClientOperationsMixin: + async def query_knowledgebase( + self, + knowledgebase_query_parameters: "_models.KnowledgebaseQueryParameters", + *, + project_name: str, + deployment_name: Optional[str] = None, + **kwargs: Any + ) -> "_models.KnowledgebaseAnswers": + """Answers the specified question using your knowledgebase. + + Answers the specified question using your knowledgebase. + + :keyword project_name: The name of the project to use. + :paramtype project_name: str + :param knowledgebase_query_parameters: Post body of the request. + :type knowledgebase_query_parameters: + ~azure.ai.language.questionanswering.models.KnowledgebaseQueryParameters + :keyword deployment_name: The name of the specific deployment of the project to use. + :paramtype deployment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: KnowledgebaseAnswers, or the result of cls(response) + :rtype: ~azure.ai.language.questionanswering.models.KnowledgebaseAnswers + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop("cls", None) # type: ClsType["_models.KnowledgebaseAnswers"] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + content_type = kwargs.pop("content_type", "application/json") # type: Optional[str] + + json = self._serialize.body(knowledgebase_query_parameters, "object") + + request = rest.build_query_knowledgebase_request( + project_name=project_name, + deployment_name=deployment_name, + json=json, + content_type=content_type, + template_url=self.query_knowledgebase.metadata["url"], + **kwargs + ) + 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) + + pipeline_response = await self._client.send_request( + request, stream=False, _return_pipeline_response=True, **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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("KnowledgebaseAnswers", pipeline_response) + + if cls: + return cls(PipelineResponse._convert(pipeline_response), deserialized, {}) + + return deserialized + + query_knowledgebase.metadata = {"url": "/:query-knowledgebases"} # type: ignore + + async def query_text( + self, text_query_parameters: "_models.TextQueryParameters", **kwargs: Any + ) -> "_models.TextAnswers": + """Answers the specified question using the provided text in the body. + + Answers the specified question using the provided text in the body. + + :param text_query_parameters: Post body of the request. + :type text_query_parameters: ~azure.ai.language.questionanswering.models.TextQueryParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :return: TextAnswers, or the result of cls(response) + :rtype: ~azure.ai.language.questionanswering.models.TextAnswers + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop("cls", None) # type: ClsType["_models.TextAnswers"] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + content_type = kwargs.pop("content_type", "application/json") # type: Optional[str] + + json = self._serialize.body(text_query_parameters, "object") + + request = rest.build_query_text_request( + json=json, content_type=content_type, template_url=self.query_text.metadata["url"], **kwargs + ) + 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) + + pipeline_response = await self._client.send_request( + request, stream=False, _return_pipeline_response=True, **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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("TextAnswers", pipeline_response) + + if cls: + return cls(PipelineResponse._convert(pipeline_response), deserialized, {}) + + return deserialized + + query_text.metadata = {"url": "/:query-text"} # type: ignore diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/__init__.py new file mode 100644 index 000000000000..0c4b0dd97763 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/__init__.py @@ -0,0 +1,77 @@ +# 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. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import AnswerSpan + from ._models_py3 import AnswerSpanRequest + from ._models_py3 import Error + from ._models_py3 import ErrorResponse + from ._models_py3 import InnerErrorModel + from ._models_py3 import KnowledgebaseAnswer + from ._models_py3 import KnowledgebaseAnswerDialog + from ._models_py3 import KnowledgebaseAnswerPrompt + from ._models_py3 import KnowledgebaseAnswerRequestContext + from ._models_py3 import KnowledgebaseAnswers + from ._models_py3 import KnowledgebaseQueryParameters + from ._models_py3 import MetadataFilter + from ._models_py3 import StrictFilters + from ._models_py3 import TextAnswer + from ._models_py3 import TextAnswers + from ._models_py3 import TextInput + from ._models_py3 import TextQueryParameters +except (SyntaxError, ImportError): + from ._models import AnswerSpan # type: ignore + from ._models import AnswerSpanRequest # type: ignore + from ._models import Error # type: ignore + from ._models import ErrorResponse # type: ignore + from ._models import InnerErrorModel # type: ignore + from ._models import KnowledgebaseAnswer # type: ignore + from ._models import KnowledgebaseAnswerDialog # type: ignore + from ._models import KnowledgebaseAnswerPrompt # type: ignore + from ._models import KnowledgebaseAnswerRequestContext # type: ignore + from ._models import KnowledgebaseAnswers # type: ignore + from ._models import KnowledgebaseQueryParameters # type: ignore + from ._models import MetadataFilter # type: ignore + from ._models import StrictFilters # type: ignore + from ._models import TextAnswer # type: ignore + from ._models import TextAnswers # type: ignore + from ._models import TextInput # type: ignore + from ._models import TextQueryParameters # type: ignore + +from ._question_answering_client_enums import ( + CompoundOperationType, + ErrorCode, + InnerErrorCode, + RankerType, + StringIndexType, +) + +__all__ = [ + "AnswerSpan", + "AnswerSpanRequest", + "Error", + "ErrorResponse", + "InnerErrorModel", + "KnowledgebaseAnswer", + "KnowledgebaseAnswerDialog", + "KnowledgebaseAnswerPrompt", + "KnowledgebaseAnswerRequestContext", + "KnowledgebaseAnswers", + "KnowledgebaseQueryParameters", + "MetadataFilter", + "StrictFilters", + "TextAnswer", + "TextAnswers", + "TextInput", + "TextQueryParameters", + "CompoundOperationType", + "ErrorCode", + "InnerErrorCode", + "RankerType", + "StringIndexType", +] diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_models.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_models.py new file mode 100644 index 000000000000..d98ed137dc45 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_models.py @@ -0,0 +1,549 @@ +# 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 azure.core.exceptions import HttpResponseError +import msrest.serialization + + +class AnswerSpan(msrest.serialization.Model): + """Answer span object of QnA. + + :param text: Predicted text of answer span. + :type text: str + :param confidence_score: Predicted score of answer span, value ranges from 0 to 1. + :type confidence_score: float + :param offset: The answer span offset from the start of answer. + :type offset: int + :param length: The length of the answer span. + :type length: int + """ + + _validation = { + "confidence_score": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "text": {"key": "text", "type": "str"}, + "confidence_score": {"key": "confidenceScore", "type": "float"}, + "offset": {"key": "offset", "type": "int"}, + "length": {"key": "length", "type": "int"}, + } + + def __init__(self, **kwargs): + super(AnswerSpan, self).__init__(**kwargs) + self.text = kwargs.get("text", None) + self.confidence_score = kwargs.get("confidence_score", None) + self.offset = kwargs.get("offset", None) + self.length = kwargs.get("length", None) + + +class AnswerSpanRequest(msrest.serialization.Model): + """To configure Answer span prediction feature. + + :param enable: Enable or disable Answer Span prediction. + :type enable: bool + :param confidence_score_threshold: Minimum threshold score required to include an answer span, + value ranges from 0 to 1. + :type confidence_score_threshold: float + :param top_answers_with_span: Number of Top answers to be considered for span prediction from 1 + to 10. + :type top_answers_with_span: int + """ + + _validation = { + "confidence_score_threshold": {"maximum": 1, "minimum": 0}, + "top_answers_with_span": {"maximum": 10, "minimum": 1}, + } + + _attribute_map = { + "enable": {"key": "enable", "type": "bool"}, + "confidence_score_threshold": {"key": "confidenceScoreThreshold", "type": "float"}, + "top_answers_with_span": {"key": "topAnswersWithSpan", "type": "int"}, + } + + def __init__(self, **kwargs): + super(AnswerSpanRequest, self).__init__(**kwargs) + self.enable = kwargs.get("enable", None) + self.confidence_score_threshold = kwargs.get("confidence_score_threshold", None) + self.top_answers_with_span = kwargs.get("top_answers_with_span", None) + + +class Error(msrest.serialization.Model): + """The error object. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. One of a server-defined set of error codes. Possible values include: + "InvalidRequest", "InvalidArgument", "Unauthorized", "Forbidden", "NotFound", + "TooManyRequests", "InternalServerError", "ServiceUnavailable". + :type code: str or ~azure.ai.language.questionanswering.models.ErrorCode + :param message: Required. A human-readable representation of the error. + :type message: str + :param target: The target of the error. + :type target: str + :param details: An array of details about specific errors that led to this reported error. + :type details: list[~azure.ai.language.questionanswering.models.Error] + :param innererror: An object containing more specific information than the current object about + the error. + :type innererror: ~azure.ai.language.questionanswering.models.InnerErrorModel + """ + + _validation = { + "code": {"required": True}, + "message": {"required": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[Error]"}, + "innererror": {"key": "innererror", "type": "InnerErrorModel"}, + } + + def __init__(self, **kwargs): + super(Error, self).__init__(**kwargs) + self.code = kwargs["code"] + self.message = kwargs["message"] + self.target = kwargs.get("target", None) + self.details = kwargs.get("details", None) + self.innererror = kwargs.get("innererror", None) + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + :param error: The error object. + :type error: ~azure.ai.language.questionanswering.models.Error + """ + + _attribute_map = { + "error": {"key": "error", "type": "Error"}, + } + + def __init__(self, **kwargs): + super(ErrorResponse, self).__init__(**kwargs) + self.error = kwargs.get("error", None) + + +class InnerErrorModel(msrest.serialization.Model): + """An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. One of a server-defined set of error codes. Possible values include: + "InvalidRequest", "InvalidParameterValue", "KnowledgeBaseNotFound", + "AzureCognitiveSearchNotFound", "AzureCognitiveSearchThrottling", "ExtractionFailure". + :type code: str or ~azure.ai.language.questionanswering.models.InnerErrorCode + :param message: Required. Error message. + :type message: str + :param details: Error details. + :type details: dict[str, str] + :param target: Error target. + :type target: str + :param innererror: An object containing more specific information than the current object about + the error. + :type innererror: ~azure.ai.language.questionanswering.models.InnerErrorModel + """ + + _validation = { + "code": {"required": True}, + "message": {"required": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "{str}"}, + "target": {"key": "target", "type": "str"}, + "innererror": {"key": "innererror", "type": "InnerErrorModel"}, + } + + def __init__(self, **kwargs): + super(InnerErrorModel, self).__init__(**kwargs) + self.code = kwargs["code"] + self.message = kwargs["message"] + self.details = kwargs.get("details", None) + self.target = kwargs.get("target", None) + self.innererror = kwargs.get("innererror", None) + + +class KnowledgebaseAnswer(msrest.serialization.Model): + """Represents Knowledgebase Answer. + + :param questions: List of questions. + :type questions: list[str] + :param answer: The Answer. + :type answer: str + :param confidence_score: Answer confidence score, value ranges from 0 to 1. + :type confidence_score: float + :param id: ID of the QnA result. + :type id: int + :param source: Source of QnA result. + :type source: str + :param metadata: Metadata associated with the answer, useful to categorize or filter question + answers. + :type metadata: dict[str, str] + :param dialog: Dialog associated with Answer. + :type dialog: ~azure.ai.language.questionanswering.models.KnowledgebaseAnswerDialog + :param answer_span: Answer span object of QnA with respect to user's question. + :type answer_span: ~azure.ai.language.questionanswering.models.AnswerSpan + """ + + _validation = { + "confidence_score": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "questions": {"key": "questions", "type": "[str]"}, + "answer": {"key": "answer", "type": "str"}, + "confidence_score": {"key": "confidenceScore", "type": "float"}, + "id": {"key": "id", "type": "int"}, + "source": {"key": "source", "type": "str"}, + "metadata": {"key": "metadata", "type": "{str}"}, + "dialog": {"key": "dialog", "type": "KnowledgebaseAnswerDialog"}, + "answer_span": {"key": "answerSpan", "type": "AnswerSpan"}, + } + + def __init__(self, **kwargs): + super(KnowledgebaseAnswer, self).__init__(**kwargs) + self.questions = kwargs.get("questions", None) + self.answer = kwargs.get("answer", None) + self.confidence_score = kwargs.get("confidence_score", None) + self.id = kwargs.get("id", None) + self.source = kwargs.get("source", None) + self.metadata = kwargs.get("metadata", None) + self.dialog = kwargs.get("dialog", None) + self.answer_span = kwargs.get("answer_span", None) + + +class KnowledgebaseAnswerDialog(msrest.serialization.Model): + """Dialog associated with Answer. + + :param is_context_only: To mark if a prompt is relevant only with a previous question or not. + If true, do not include this QnA as search result for queries without context; otherwise, if + false, ignores context and includes this QnA in search result. + :type is_context_only: bool + :param prompts: List of 0 to 20 prompts associated with the answer. + :type prompts: list[~azure.ai.language.questionanswering.models.KnowledgebaseAnswerPrompt] + """ + + _validation = { + "prompts": {"max_items": 20, "min_items": 0}, + } + + _attribute_map = { + "is_context_only": {"key": "isContextOnly", "type": "bool"}, + "prompts": {"key": "prompts", "type": "[KnowledgebaseAnswerPrompt]"}, + } + + def __init__(self, **kwargs): + super(KnowledgebaseAnswerDialog, self).__init__(**kwargs) + self.is_context_only = kwargs.get("is_context_only", None) + self.prompts = kwargs.get("prompts", None) + + +class KnowledgebaseAnswerPrompt(msrest.serialization.Model): + """Prompt for an answer. + + :param display_order: Index of the prompt - used in ordering of the prompts. + :type display_order: int + :param qna_id: QnA ID corresponding to the prompt. + :type qna_id: int + :param display_text: Text displayed to represent a follow up question prompt. + :type display_text: str + """ + + _validation = { + "display_text": {"max_length": 200, "min_length": 0}, + } + + _attribute_map = { + "display_order": {"key": "displayOrder", "type": "int"}, + "qna_id": {"key": "qnaId", "type": "int"}, + "display_text": {"key": "displayText", "type": "str"}, + } + + def __init__(self, **kwargs): + super(KnowledgebaseAnswerPrompt, self).__init__(**kwargs) + self.display_order = kwargs.get("display_order", None) + self.qna_id = kwargs.get("qna_id", None) + self.display_text = kwargs.get("display_text", None) + + +class KnowledgebaseAnswerRequestContext(msrest.serialization.Model): + """Context object with previous QnA's information. + + All required parameters must be populated in order to send to Azure. + + :param previous_qna_id: Required. Previous turn top answer result QnA ID. + :type previous_qna_id: int + :param previous_user_query: Previous user query. + :type previous_user_query: str + """ + + _validation = { + "previous_qna_id": {"required": True}, + } + + _attribute_map = { + "previous_qna_id": {"key": "previousQnaId", "type": "int"}, + "previous_user_query": {"key": "previousUserQuery", "type": "str"}, + } + + def __init__(self, **kwargs): + super(KnowledgebaseAnswerRequestContext, self).__init__(**kwargs) + self.previous_qna_id = kwargs["previous_qna_id"] + self.previous_user_query = kwargs.get("previous_user_query", None) + + +class KnowledgebaseAnswers(msrest.serialization.Model): + """Represents List of Question Answers. + + :param answers: Represents Answer Result list. + :type answers: list[~azure.ai.language.questionanswering.models.KnowledgebaseAnswer] + """ + + _attribute_map = { + "answers": {"key": "answers", "type": "[KnowledgebaseAnswer]"}, + } + + def __init__(self, **kwargs): + super(KnowledgebaseAnswers, self).__init__(**kwargs) + self.answers = kwargs.get("answers", None) + + +class KnowledgebaseQueryParameters(msrest.serialization.Model): + """The question parameters to answer using a knowledgebase. + + :param qna_id: Exact QnA ID to fetch from the knowledgebase, this field takes priority over + question. + :type qna_id: int + :param question: User question to query against the knowledge base. + :type question: str + :param top: Max number of answers to be returned for the question. + :type top: int + :param user_id: Unique identifier for the user. + :type user_id: str + :param confidence_score_threshold: Minimum threshold score for answers, value ranges from 0 to + 1. + :type confidence_score_threshold: float + :param context: Context object with previous QnA's information. + :type context: ~azure.ai.language.questionanswering.models.KnowledgebaseAnswerRequestContext + :param ranker_type: (Optional) Set to 'QuestionOnly' for using a question only Ranker. Possible + values include: "Default", "QuestionOnly". + :type ranker_type: str or ~azure.ai.language.questionanswering.models.RankerType + :param strict_filters: Filter QnAs based on give metadata list and knowledgebase source names. + :type strict_filters: ~azure.ai.language.questionanswering.models.StrictFilters + :param answer_span_request: To configure Answer span prediction feature. + :type answer_span_request: ~azure.ai.language.questionanswering.models.AnswerSpanRequest + :param include_unstructured_sources: (Optional) Flag to enable Query over Unstructured Sources. + :type include_unstructured_sources: bool + """ + + _validation = { + "confidence_score_threshold": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "qna_id": {"key": "qnaId", "type": "int"}, + "question": {"key": "question", "type": "str"}, + "top": {"key": "top", "type": "int"}, + "user_id": {"key": "userId", "type": "str"}, + "confidence_score_threshold": {"key": "confidenceScoreThreshold", "type": "float"}, + "context": {"key": "context", "type": "KnowledgebaseAnswerRequestContext"}, + "ranker_type": {"key": "rankerType", "type": "str"}, + "strict_filters": {"key": "strictFilters", "type": "StrictFilters"}, + "answer_span_request": {"key": "answerSpanRequest", "type": "AnswerSpanRequest"}, + "include_unstructured_sources": {"key": "includeUnstructuredSources", "type": "bool"}, + } + + def __init__(self, **kwargs): + super(KnowledgebaseQueryParameters, self).__init__(**kwargs) + self.qna_id = kwargs.get("qna_id", None) + self.question = kwargs.get("question", None) + self.top = kwargs.get("top", None) + self.user_id = kwargs.get("user_id", None) + self.confidence_score_threshold = kwargs.get("confidence_score_threshold", None) + self.context = kwargs.get("context", None) + self.ranker_type = kwargs.get("ranker_type", None) + self.strict_filters = kwargs.get("strict_filters", None) + self.answer_span_request = kwargs.get("answer_span_request", None) + self.include_unstructured_sources = kwargs.get("include_unstructured_sources", None) + + +class MetadataFilter(msrest.serialization.Model): + """Find QnAs that are associated with the given list of metadata. + + :param metadata: Dictionary of :code:``. + :type metadata: dict[str, str] + :param compound_operation: (Optional) Set to 'OR' for joining metadata using 'OR' operation. + Possible values include: "AND", "OR". + :type compound_operation: str or + ~azure.ai.language.questionanswering.models.CompoundOperationType + """ + + _attribute_map = { + "metadata": {"key": "metadata", "type": "{str}"}, + "compound_operation": {"key": "compoundOperation", "type": "str"}, + } + + def __init__(self, **kwargs): + super(MetadataFilter, self).__init__(**kwargs) + self.metadata = kwargs.get("metadata", None) + self.compound_operation = kwargs.get("compound_operation", None) + + +class StrictFilters(msrest.serialization.Model): + """filters over knowledgebase. + + :param metadata_filter: Find QnAs that are associated with the given list of metadata. + :type metadata_filter: ~azure.ai.language.questionanswering.models.MetadataFilter + :param source_filter: Find QnAs that are associated with the given list of sources in + knowledgebase. + :type source_filter: list[str] + :param compound_operation: (Optional) Set to 'OR' for joining metadata using 'OR' operation. + Possible values include: "AND", "OR". + :type compound_operation: str or + ~azure.ai.language.questionanswering.models.CompoundOperationType + """ + + _attribute_map = { + "metadata_filter": {"key": "metadataFilter", "type": "MetadataFilter"}, + "source_filter": {"key": "sourceFilter", "type": "[str]"}, + "compound_operation": {"key": "compoundOperation", "type": "str"}, + } + + def __init__(self, **kwargs): + super(StrictFilters, self).__init__(**kwargs) + self.metadata_filter = kwargs.get("metadata_filter", None) + self.source_filter = kwargs.get("source_filter", None) + self.compound_operation = kwargs.get("compound_operation", None) + + +class TextAnswer(msrest.serialization.Model): + """Represents answer result. + + :param answer: Answer. + :type answer: str + :param confidence_score: answer confidence score, value ranges from 0 to 1. + :type confidence_score: float + :param id: record ID. + :type id: str + :param answer_span: Answer span object with respect to user's question. + :type answer_span: ~azure.ai.language.questionanswering.models.AnswerSpan + :param offset: The sentence offset from the start of the document. + :type offset: int + :param length: The length of the sentence. + :type length: int + """ + + _validation = { + "confidence_score": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "answer": {"key": "answer", "type": "str"}, + "confidence_score": {"key": "confidenceScore", "type": "float"}, + "id": {"key": "id", "type": "str"}, + "answer_span": {"key": "answerSpan", "type": "AnswerSpan"}, + "offset": {"key": "offset", "type": "int"}, + "length": {"key": "length", "type": "int"}, + } + + def __init__(self, **kwargs): + super(TextAnswer, self).__init__(**kwargs) + self.answer = kwargs.get("answer", None) + self.confidence_score = kwargs.get("confidence_score", None) + self.id = kwargs.get("id", None) + self.answer_span = kwargs.get("answer_span", None) + self.offset = kwargs.get("offset", None) + self.length = kwargs.get("length", None) + + +class TextAnswers(msrest.serialization.Model): + """Represents the answer results. + + :param answers: Represents the answer results. + :type answers: list[~azure.ai.language.questionanswering.models.TextAnswer] + """ + + _attribute_map = { + "answers": {"key": "answers", "type": "[TextAnswer]"}, + } + + def __init__(self, **kwargs): + super(TextAnswers, self).__init__(**kwargs) + self.answers = kwargs.get("answers", None) + + +class TextInput(msrest.serialization.Model): + """Represent input text record to be queried. + + All required parameters must be populated in order to send to Azure. + + :param id: Required. Unique identifier for the text record. + :type id: str + :param text: Required. Text contents of the record. + :type text: str + """ + + _validation = { + "id": {"required": True}, + "text": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "text": {"key": "text", "type": "str"}, + } + + def __init__(self, **kwargs): + super(TextInput, self).__init__(**kwargs) + self.id = kwargs["id"] + self.text = kwargs["text"] + + +class TextQueryParameters(msrest.serialization.Model): + """The question and text record parameters to answer. + + All required parameters must be populated in order to send to Azure. + + :param question: Required. User question to query against the given text records. + :type question: str + :param records: Required. Text records to be searched for given question. + :type records: list[~azure.ai.language.questionanswering.models.TextInput] + :param language: Language of the text records. This is BCP-47 representation of a language. For + example, use "en" for English; "es" for Spanish etc. If not set, use "en" for English as + default. + :type language: str + :param string_index_type: Specifies the method used to interpret string offsets. Defaults to + Text Elements (Graphemes) according to Unicode v8.0.0. For additional information see + https://aka.ms/text-analytics-offsets. Possible values include: "TextElements_v8", + "UnicodeCodePoint", "Utf16CodeUnit". Default value: "TextElements_v8". + :type string_index_type: str or ~azure.ai.language.questionanswering.models.StringIndexType + """ + + _validation = { + "question": {"required": True}, + "records": {"required": True}, + } + + _attribute_map = { + "question": {"key": "question", "type": "str"}, + "records": {"key": "records", "type": "[TextInput]"}, + "language": {"key": "language", "type": "str"}, + "string_index_type": {"key": "stringIndexType", "type": "str"}, + } + + def __init__(self, **kwargs): + super(TextQueryParameters, self).__init__(**kwargs) + self.question = kwargs["question"] + self.records = kwargs["records"] + self.language = kwargs.get("language", None) + self.string_index_type = kwargs.get("string_index_type", "TextElements_v8") diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_models_py3.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_models_py3.py new file mode 100644 index 000000000000..e0cf8d3d9fdf --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_models_py3.py @@ -0,0 +1,656 @@ +# 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 Dict, List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._question_answering_client_enums import * + + +class AnswerSpan(msrest.serialization.Model): + """Answer span object of QnA. + + :param text: Predicted text of answer span. + :type text: str + :param confidence_score: Predicted score of answer span, value ranges from 0 to 1. + :type confidence_score: float + :param offset: The answer span offset from the start of answer. + :type offset: int + :param length: The length of the answer span. + :type length: int + """ + + _validation = { + "confidence_score": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "text": {"key": "text", "type": "str"}, + "confidence_score": {"key": "confidenceScore", "type": "float"}, + "offset": {"key": "offset", "type": "int"}, + "length": {"key": "length", "type": "int"}, + } + + def __init__( + self, + *, + text: Optional[str] = None, + confidence_score: Optional[float] = None, + offset: Optional[int] = None, + length: Optional[int] = None, + **kwargs + ): + super(AnswerSpan, self).__init__(**kwargs) + self.text = text + self.confidence_score = confidence_score + self.offset = offset + self.length = length + + +class AnswerSpanRequest(msrest.serialization.Model): + """To configure Answer span prediction feature. + + :param enable: Enable or disable Answer Span prediction. + :type enable: bool + :param confidence_score_threshold: Minimum threshold score required to include an answer span, + value ranges from 0 to 1. + :type confidence_score_threshold: float + :param top_answers_with_span: Number of Top answers to be considered for span prediction from 1 + to 10. + :type top_answers_with_span: int + """ + + _validation = { + "confidence_score_threshold": {"maximum": 1, "minimum": 0}, + "top_answers_with_span": {"maximum": 10, "minimum": 1}, + } + + _attribute_map = { + "enable": {"key": "enable", "type": "bool"}, + "confidence_score_threshold": {"key": "confidenceScoreThreshold", "type": "float"}, + "top_answers_with_span": {"key": "topAnswersWithSpan", "type": "int"}, + } + + def __init__( + self, + *, + enable: Optional[bool] = None, + confidence_score_threshold: Optional[float] = None, + top_answers_with_span: Optional[int] = None, + **kwargs + ): + super(AnswerSpanRequest, self).__init__(**kwargs) + self.enable = enable + self.confidence_score_threshold = confidence_score_threshold + self.top_answers_with_span = top_answers_with_span + + +class Error(msrest.serialization.Model): + """The error object. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. One of a server-defined set of error codes. Possible values include: + "InvalidRequest", "InvalidArgument", "Unauthorized", "Forbidden", "NotFound", + "TooManyRequests", "InternalServerError", "ServiceUnavailable". + :type code: str or ~azure.ai.language.questionanswering.models.ErrorCode + :param message: Required. A human-readable representation of the error. + :type message: str + :param target: The target of the error. + :type target: str + :param details: An array of details about specific errors that led to this reported error. + :type details: list[~azure.ai.language.questionanswering.models.Error] + :param innererror: An object containing more specific information than the current object about + the error. + :type innererror: ~azure.ai.language.questionanswering.models.InnerErrorModel + """ + + _validation = { + "code": {"required": True}, + "message": {"required": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "details": {"key": "details", "type": "[Error]"}, + "innererror": {"key": "innererror", "type": "InnerErrorModel"}, + } + + def __init__( + self, + *, + code: Union[str, "ErrorCode"], + message: str, + target: Optional[str] = None, + details: Optional[List["Error"]] = None, + innererror: Optional["InnerErrorModel"] = None, + **kwargs + ): + super(Error, self).__init__(**kwargs) + self.code = code + self.message = message + self.target = target + self.details = details + self.innererror = innererror + + +class ErrorResponse(msrest.serialization.Model): + """Error response. + + :param error: The error object. + :type error: ~azure.ai.language.questionanswering.models.Error + """ + + _attribute_map = { + "error": {"key": "error", "type": "Error"}, + } + + def __init__(self, *, error: Optional["Error"] = None, **kwargs): + super(ErrorResponse, self).__init__(**kwargs) + self.error = error + + +class InnerErrorModel(msrest.serialization.Model): + """An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + + All required parameters must be populated in order to send to Azure. + + :param code: Required. One of a server-defined set of error codes. Possible values include: + "InvalidRequest", "InvalidParameterValue", "KnowledgeBaseNotFound", + "AzureCognitiveSearchNotFound", "AzureCognitiveSearchThrottling", "ExtractionFailure". + :type code: str or ~azure.ai.language.questionanswering.models.InnerErrorCode + :param message: Required. Error message. + :type message: str + :param details: Error details. + :type details: dict[str, str] + :param target: Error target. + :type target: str + :param innererror: An object containing more specific information than the current object about + the error. + :type innererror: ~azure.ai.language.questionanswering.models.InnerErrorModel + """ + + _validation = { + "code": {"required": True}, + "message": {"required": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + "details": {"key": "details", "type": "{str}"}, + "target": {"key": "target", "type": "str"}, + "innererror": {"key": "innererror", "type": "InnerErrorModel"}, + } + + def __init__( + self, + *, + code: Union[str, "InnerErrorCode"], + message: str, + details: Optional[Dict[str, str]] = None, + target: Optional[str] = None, + innererror: Optional["InnerErrorModel"] = None, + **kwargs + ): + super(InnerErrorModel, self).__init__(**kwargs) + self.code = code + self.message = message + self.details = details + self.target = target + self.innererror = innererror + + +class KnowledgebaseAnswer(msrest.serialization.Model): + """Represents Knowledgebase Answer. + + :param questions: List of questions. + :type questions: list[str] + :param answer: The Answer. + :type answer: str + :param confidence_score: Answer confidence score, value ranges from 0 to 1. + :type confidence_score: float + :param id: ID of the QnA result. + :type id: int + :param source: Source of QnA result. + :type source: str + :param metadata: Metadata associated with the answer, useful to categorize or filter question + answers. + :type metadata: dict[str, str] + :param dialog: Dialog associated with Answer. + :type dialog: ~azure.ai.language.questionanswering.models.KnowledgebaseAnswerDialog + :param answer_span: Answer span object of QnA with respect to user's question. + :type answer_span: ~azure.ai.language.questionanswering.models.AnswerSpan + """ + + _validation = { + "confidence_score": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "questions": {"key": "questions", "type": "[str]"}, + "answer": {"key": "answer", "type": "str"}, + "confidence_score": {"key": "confidenceScore", "type": "float"}, + "id": {"key": "id", "type": "int"}, + "source": {"key": "source", "type": "str"}, + "metadata": {"key": "metadata", "type": "{str}"}, + "dialog": {"key": "dialog", "type": "KnowledgebaseAnswerDialog"}, + "answer_span": {"key": "answerSpan", "type": "AnswerSpan"}, + } + + def __init__( + self, + *, + questions: Optional[List[str]] = None, + answer: Optional[str] = None, + confidence_score: Optional[float] = None, + id: Optional[int] = None, + source: Optional[str] = None, + metadata: Optional[Dict[str, str]] = None, + dialog: Optional["KnowledgebaseAnswerDialog"] = None, + answer_span: Optional["AnswerSpan"] = None, + **kwargs + ): + super(KnowledgebaseAnswer, self).__init__(**kwargs) + self.questions = questions + self.answer = answer + self.confidence_score = confidence_score + self.id = id + self.source = source + self.metadata = metadata + self.dialog = dialog + self.answer_span = answer_span + + +class KnowledgebaseAnswerDialog(msrest.serialization.Model): + """Dialog associated with Answer. + + :param is_context_only: To mark if a prompt is relevant only with a previous question or not. + If true, do not include this QnA as search result for queries without context; otherwise, if + false, ignores context and includes this QnA in search result. + :type is_context_only: bool + :param prompts: List of 0 to 20 prompts associated with the answer. + :type prompts: list[~azure.ai.language.questionanswering.models.KnowledgebaseAnswerPrompt] + """ + + _validation = { + "prompts": {"max_items": 20, "min_items": 0}, + } + + _attribute_map = { + "is_context_only": {"key": "isContextOnly", "type": "bool"}, + "prompts": {"key": "prompts", "type": "[KnowledgebaseAnswerPrompt]"}, + } + + def __init__( + self, + *, + is_context_only: Optional[bool] = None, + prompts: Optional[List["KnowledgebaseAnswerPrompt"]] = None, + **kwargs + ): + super(KnowledgebaseAnswerDialog, self).__init__(**kwargs) + self.is_context_only = is_context_only + self.prompts = prompts + + +class KnowledgebaseAnswerPrompt(msrest.serialization.Model): + """Prompt for an answer. + + :param display_order: Index of the prompt - used in ordering of the prompts. + :type display_order: int + :param qna_id: QnA ID corresponding to the prompt. + :type qna_id: int + :param display_text: Text displayed to represent a follow up question prompt. + :type display_text: str + """ + + _validation = { + "display_text": {"max_length": 200, "min_length": 0}, + } + + _attribute_map = { + "display_order": {"key": "displayOrder", "type": "int"}, + "qna_id": {"key": "qnaId", "type": "int"}, + "display_text": {"key": "displayText", "type": "str"}, + } + + def __init__( + self, + *, + display_order: Optional[int] = None, + qna_id: Optional[int] = None, + display_text: Optional[str] = None, + **kwargs + ): + super(KnowledgebaseAnswerPrompt, self).__init__(**kwargs) + self.display_order = display_order + self.qna_id = qna_id + self.display_text = display_text + + +class KnowledgebaseAnswerRequestContext(msrest.serialization.Model): + """Context object with previous QnA's information. + + All required parameters must be populated in order to send to Azure. + + :param previous_qna_id: Required. Previous turn top answer result QnA ID. + :type previous_qna_id: int + :param previous_user_query: Previous user query. + :type previous_user_query: str + """ + + _validation = { + "previous_qna_id": {"required": True}, + } + + _attribute_map = { + "previous_qna_id": {"key": "previousQnaId", "type": "int"}, + "previous_user_query": {"key": "previousUserQuery", "type": "str"}, + } + + def __init__(self, *, previous_qna_id: int, previous_user_query: Optional[str] = None, **kwargs): + super(KnowledgebaseAnswerRequestContext, self).__init__(**kwargs) + self.previous_qna_id = previous_qna_id + self.previous_user_query = previous_user_query + + +class KnowledgebaseAnswers(msrest.serialization.Model): + """Represents List of Question Answers. + + :param answers: Represents Answer Result list. + :type answers: list[~azure.ai.language.questionanswering.models.KnowledgebaseAnswer] + """ + + _attribute_map = { + "answers": {"key": "answers", "type": "[KnowledgebaseAnswer]"}, + } + + def __init__(self, *, answers: Optional[List["KnowledgebaseAnswer"]] = None, **kwargs): + super(KnowledgebaseAnswers, self).__init__(**kwargs) + self.answers = answers + + +class KnowledgebaseQueryParameters(msrest.serialization.Model): + """The question parameters to answer using a knowledgebase. + + :param qna_id: Exact QnA ID to fetch from the knowledgebase, this field takes priority over + question. + :type qna_id: int + :param question: User question to query against the knowledge base. + :type question: str + :param top: Max number of answers to be returned for the question. + :type top: int + :param user_id: Unique identifier for the user. + :type user_id: str + :param confidence_score_threshold: Minimum threshold score for answers, value ranges from 0 to + 1. + :type confidence_score_threshold: float + :param context: Context object with previous QnA's information. + :type context: ~azure.ai.language.questionanswering.models.KnowledgebaseAnswerRequestContext + :param ranker_type: (Optional) Set to 'QuestionOnly' for using a question only Ranker. Possible + values include: "Default", "QuestionOnly". + :type ranker_type: str or ~azure.ai.language.questionanswering.models.RankerType + :param strict_filters: Filter QnAs based on give metadata list and knowledgebase source names. + :type strict_filters: ~azure.ai.language.questionanswering.models.StrictFilters + :param answer_span_request: To configure Answer span prediction feature. + :type answer_span_request: ~azure.ai.language.questionanswering.models.AnswerSpanRequest + :param include_unstructured_sources: (Optional) Flag to enable Query over Unstructured Sources. + :type include_unstructured_sources: bool + """ + + _validation = { + "confidence_score_threshold": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "qna_id": {"key": "qnaId", "type": "int"}, + "question": {"key": "question", "type": "str"}, + "top": {"key": "top", "type": "int"}, + "user_id": {"key": "userId", "type": "str"}, + "confidence_score_threshold": {"key": "confidenceScoreThreshold", "type": "float"}, + "context": {"key": "context", "type": "KnowledgebaseAnswerRequestContext"}, + "ranker_type": {"key": "rankerType", "type": "str"}, + "strict_filters": {"key": "strictFilters", "type": "StrictFilters"}, + "answer_span_request": {"key": "answerSpanRequest", "type": "AnswerSpanRequest"}, + "include_unstructured_sources": {"key": "includeUnstructuredSources", "type": "bool"}, + } + + def __init__( + self, + *, + qna_id: Optional[int] = None, + question: Optional[str] = None, + top: Optional[int] = None, + user_id: Optional[str] = None, + confidence_score_threshold: Optional[float] = None, + context: Optional["KnowledgebaseAnswerRequestContext"] = None, + ranker_type: Optional[Union[str, "RankerType"]] = None, + strict_filters: Optional["StrictFilters"] = None, + answer_span_request: Optional["AnswerSpanRequest"] = None, + include_unstructured_sources: Optional[bool] = None, + **kwargs + ): + super(KnowledgebaseQueryParameters, self).__init__(**kwargs) + self.qna_id = qna_id + self.question = question + self.top = top + self.user_id = user_id + self.confidence_score_threshold = confidence_score_threshold + self.context = context + self.ranker_type = ranker_type + self.strict_filters = strict_filters + self.answer_span_request = answer_span_request + self.include_unstructured_sources = include_unstructured_sources + + +class MetadataFilter(msrest.serialization.Model): + """Find QnAs that are associated with the given list of metadata. + + :param metadata: Dictionary of :code:``. + :type metadata: dict[str, str] + :param compound_operation: (Optional) Set to 'OR' for joining metadata using 'OR' operation. + Possible values include: "AND", "OR". + :type compound_operation: str or + ~azure.ai.language.questionanswering.models.CompoundOperationType + """ + + _attribute_map = { + "metadata": {"key": "metadata", "type": "{str}"}, + "compound_operation": {"key": "compoundOperation", "type": "str"}, + } + + def __init__( + self, + *, + metadata: Optional[Dict[str, str]] = None, + compound_operation: Optional[Union[str, "CompoundOperationType"]] = None, + **kwargs + ): + super(MetadataFilter, self).__init__(**kwargs) + self.metadata = metadata + self.compound_operation = compound_operation + + +class StrictFilters(msrest.serialization.Model): + """filters over knowledgebase. + + :param metadata_filter: Find QnAs that are associated with the given list of metadata. + :type metadata_filter: ~azure.ai.language.questionanswering.models.MetadataFilter + :param source_filter: Find QnAs that are associated with the given list of sources in + knowledgebase. + :type source_filter: list[str] + :param compound_operation: (Optional) Set to 'OR' for joining metadata using 'OR' operation. + Possible values include: "AND", "OR". + :type compound_operation: str or + ~azure.ai.language.questionanswering.models.CompoundOperationType + """ + + _attribute_map = { + "metadata_filter": {"key": "metadataFilter", "type": "MetadataFilter"}, + "source_filter": {"key": "sourceFilter", "type": "[str]"}, + "compound_operation": {"key": "compoundOperation", "type": "str"}, + } + + def __init__( + self, + *, + metadata_filter: Optional["MetadataFilter"] = None, + source_filter: Optional[List[str]] = None, + compound_operation: Optional[Union[str, "CompoundOperationType"]] = None, + **kwargs + ): + super(StrictFilters, self).__init__(**kwargs) + self.metadata_filter = metadata_filter + self.source_filter = source_filter + self.compound_operation = compound_operation + + +class TextAnswer(msrest.serialization.Model): + """Represents answer result. + + :param answer: Answer. + :type answer: str + :param confidence_score: answer confidence score, value ranges from 0 to 1. + :type confidence_score: float + :param id: record ID. + :type id: str + :param answer_span: Answer span object with respect to user's question. + :type answer_span: ~azure.ai.language.questionanswering.models.AnswerSpan + :param offset: The sentence offset from the start of the document. + :type offset: int + :param length: The length of the sentence. + :type length: int + """ + + _validation = { + "confidence_score": {"maximum": 1, "minimum": 0}, + } + + _attribute_map = { + "answer": {"key": "answer", "type": "str"}, + "confidence_score": {"key": "confidenceScore", "type": "float"}, + "id": {"key": "id", "type": "str"}, + "answer_span": {"key": "answerSpan", "type": "AnswerSpan"}, + "offset": {"key": "offset", "type": "int"}, + "length": {"key": "length", "type": "int"}, + } + + def __init__( + self, + *, + answer: Optional[str] = None, + confidence_score: Optional[float] = None, + id: Optional[str] = None, + answer_span: Optional["AnswerSpan"] = None, + offset: Optional[int] = None, + length: Optional[int] = None, + **kwargs + ): + super(TextAnswer, self).__init__(**kwargs) + self.answer = answer + self.confidence_score = confidence_score + self.id = id + self.answer_span = answer_span + self.offset = offset + self.length = length + + +class TextAnswers(msrest.serialization.Model): + """Represents the answer results. + + :param answers: Represents the answer results. + :type answers: list[~azure.ai.language.questionanswering.models.TextAnswer] + """ + + _attribute_map = { + "answers": {"key": "answers", "type": "[TextAnswer]"}, + } + + def __init__(self, *, answers: Optional[List["TextAnswer"]] = None, **kwargs): + super(TextAnswers, self).__init__(**kwargs) + self.answers = answers + + +class TextInput(msrest.serialization.Model): + """Represent input text record to be queried. + + All required parameters must be populated in order to send to Azure. + + :param id: Required. Unique identifier for the text record. + :type id: str + :param text: Required. Text contents of the record. + :type text: str + """ + + _validation = { + "id": {"required": True}, + "text": {"required": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "text": {"key": "text", "type": "str"}, + } + + def __init__(self, *, id: str, text: str, **kwargs): + super(TextInput, self).__init__(**kwargs) + self.id = id + self.text = text + + +class TextQueryParameters(msrest.serialization.Model): + """The question and text record parameters to answer. + + All required parameters must be populated in order to send to Azure. + + :param question: Required. User question to query against the given text records. + :type question: str + :param records: Required. Text records to be searched for given question. + :type records: list[~azure.ai.language.questionanswering.models.TextInput] + :param language: Language of the text records. This is BCP-47 representation of a language. For + example, use "en" for English; "es" for Spanish etc. If not set, use "en" for English as + default. + :type language: str + :param string_index_type: Specifies the method used to interpret string offsets. Defaults to + Text Elements (Graphemes) according to Unicode v8.0.0. For additional information see + https://aka.ms/text-analytics-offsets. Possible values include: "TextElements_v8", + "UnicodeCodePoint", "Utf16CodeUnit". Default value: "TextElements_v8". + :type string_index_type: str or ~azure.ai.language.questionanswering.models.StringIndexType + """ + + _validation = { + "question": {"required": True}, + "records": {"required": True}, + } + + _attribute_map = { + "question": {"key": "question", "type": "str"}, + "records": {"key": "records", "type": "[TextInput]"}, + "language": {"key": "language", "type": "str"}, + "string_index_type": {"key": "stringIndexType", "type": "str"}, + } + + def __init__( + self, + *, + question: str, + records: List["TextInput"], + language: Optional[str] = None, + string_index_type: Optional[Union[str, "StringIndexType"]] = "TextElements_v8", + **kwargs + ): + super(TextQueryParameters, self).__init__(**kwargs) + self.question = question + self.records = records + self.language = language + self.string_index_type = string_index_type diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_question_answering_client_enums.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_question_answering_client_enums.py new file mode 100644 index 000000000000..aace462c8469 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/models/_question_answering_client_enums.py @@ -0,0 +1,83 @@ +# 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 enum import Enum, EnumMeta +from six import with_metaclass + + +class _CaseInsensitiveEnumMeta(EnumMeta): + def __getitem__(self, name): + return super().__getitem__(name.upper()) + + def __getattr__(cls, name): + """Return the enum member matching `name` + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + """ + try: + return cls._member_map_[name.upper()] + except KeyError: + raise AttributeError(name) + + +class CompoundOperationType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """(Optional) Set to 'OR' for joining metadata using 'OR' operation.""" + + AND_ENUM = "AND" + OR_ENUM = "OR" + + +class ErrorCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Human-readable error code.""" + + INVALID_REQUEST = "InvalidRequest" + INVALID_ARGUMENT = "InvalidArgument" + UNAUTHORIZED = "Unauthorized" + FORBIDDEN = "Forbidden" + NOT_FOUND = "NotFound" + TOO_MANY_REQUESTS = "TooManyRequests" + INTERNAL_SERVER_ERROR = "InternalServerError" + SERVICE_UNAVAILABLE = "ServiceUnavailable" + + +class InnerErrorCode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Human-readable error code.""" + + INVALID_REQUEST = "InvalidRequest" + INVALID_PARAMETER_VALUE = "InvalidParameterValue" + KNOWLEDGE_BASE_NOT_FOUND = "KnowledgeBaseNotFound" + AZURE_COGNITIVE_SEARCH_NOT_FOUND = "AzureCognitiveSearchNotFound" + AZURE_COGNITIVE_SEARCH_THROTTLING = "AzureCognitiveSearchThrottling" + EXTRACTION_FAILURE = "ExtractionFailure" + + +class RankerType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """(Optional) Set to 'QuestionOnly' for using a question only Ranker.""" + + DEFAULT = "Default" + QUESTION_ONLY = "QuestionOnly" + + +class StringIndexType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Specifies the method used to interpret string offsets. Defaults to Text Elements (Graphemes) + according to Unicode v8.0.0. For additional information see + https://aka.ms/text-analytics-offsets. + """ + + #: Returned offset and length values will correspond to TextElements (Graphemes and Grapheme + #: clusters) confirming to the Unicode 8.0.0 standard. Use this option if your application is + #: written in .Net Framework or .Net Core and you will be using StringInfo. + TEXT_ELEMENTS_V8 = "TextElements_v8" + #: Returned offset and length values will correspond to Unicode code points. Use this option if + #: your application is written in a language that support Unicode, for example Python. + UNICODE_CODE_POINT = "UnicodeCodePoint" + #: Returned offset and length values will correspond to UTF-16 code units. Use this option if your + #: application is written in a language that support Unicode, for example Java, JavaScript. + UTF16_CODE_UNIT = "Utf16CodeUnit" diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/operations/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/operations/__init__.py new file mode 100644 index 000000000000..200be9f1c22e --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/operations/__init__.py @@ -0,0 +1,13 @@ +# 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 ._question_answering_client_operations import QuestionAnsweringClientOperationsMixin + +__all__ = [ + "QuestionAnsweringClientOperationsMixin", +] diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/operations/_question_answering_client_operations.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/operations/_question_answering_client_operations.py new file mode 100644 index 000000000000..280cb22fc259 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/operations/_question_answering_client_operations.py @@ -0,0 +1,144 @@ +# 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. +# -------------------------------------------------------------------------- +import functools +from typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest + +from .. import models as _models, rest + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar("T") + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + + +class QuestionAnsweringClientOperationsMixin(object): + def query_knowledgebase( + self, + knowledgebase_query_parameters, # type: "_models.KnowledgebaseQueryParameters" + **kwargs # type: Any + ): + # type: (...) -> "_models.KnowledgebaseAnswers" + """Answers the specified question using your knowledgebase. + + Answers the specified question using your knowledgebase. + + :keyword project_name: The name of the project to use. + :paramtype project_name: str + :param knowledgebase_query_parameters: Post body of the request. + :type knowledgebase_query_parameters: + ~azure.ai.language.questionanswering.models.KnowledgebaseQueryParameters + :keyword deployment_name: The name of the specific deployment of the project to use. + :paramtype deployment_name: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: KnowledgebaseAnswers, or the result of cls(response) + :rtype: ~azure.ai.language.questionanswering.models.KnowledgebaseAnswers + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop("cls", None) # type: ClsType["_models.KnowledgebaseAnswers"] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + content_type = kwargs.pop("content_type", "application/json") # type: Optional[str] + project_name = kwargs.pop("project_name") # type: str + deployment_name = kwargs.pop("deployment_name", None) # type: Optional[str] + + json = self._serialize.body(knowledgebase_query_parameters, "object") + + request = rest.build_query_knowledgebase_request( + project_name=project_name, + deployment_name=deployment_name, + json=json, + content_type=content_type, + template_url=self.query_knowledgebase.metadata["url"], + **kwargs + ) + 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) + + pipeline_response = self._client.send_request(request, stream=False, _return_pipeline_response=True, **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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("KnowledgebaseAnswers", pipeline_response) + + if cls: + return cls(PipelineResponse._convert(pipeline_response), deserialized, {}) + + return deserialized + + query_knowledgebase.metadata = {"url": "/:query-knowledgebases"} # type: ignore + + def query_text( + self, + text_query_parameters, # type: "_models.TextQueryParameters" + **kwargs # type: Any + ): + # type: (...) -> "_models.TextAnswers" + """Answers the specified question using the provided text in the body. + + Answers the specified question using the provided text in the body. + + :param text_query_parameters: Post body of the request. + :type text_query_parameters: ~azure.ai.language.questionanswering.models.TextQueryParameters + :keyword callable cls: A custom type or function that will be passed the direct response + :return: TextAnswers, or the result of cls(response) + :rtype: ~azure.ai.language.questionanswering.models.TextAnswers + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop("cls", None) # type: ClsType["_models.TextAnswers"] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + content_type = kwargs.pop("content_type", "application/json") # type: Optional[str] + + json = self._serialize.body(text_query_parameters, "object") + + request = rest.build_query_text_request( + json=json, content_type=content_type, template_url=self.query_text.metadata["url"], **kwargs + ) + 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) + + pipeline_response = self._client.send_request(request, stream=False, _return_pipeline_response=True, **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) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("TextAnswers", pipeline_response) + + if cls: + return cls(PipelineResponse._convert(pipeline_response), deserialized, {}) + + return deserialized + + query_text.metadata = {"url": "/:query-text"} # type: ignore diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/py.typed b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/__init__.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/__init__.py new file mode 100644 index 000000000000..4fdfbbf6f9e2 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/__init__.py @@ -0,0 +1,19 @@ +# 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. +# -------------------------------------------------------------------------- + +try: + from ._request_builders_py3 import build_query_knowledgebase_request + from ._request_builders_py3 import build_query_text_request +except (SyntaxError, ImportError): + from ._request_builders import build_query_knowledgebase_request # type: ignore + from ._request_builders import build_query_text_request # type: ignore + +__all__ = [ + 'build_query_knowledgebase_request', + 'build_query_text_request', +] diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/_request_builders.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/_request_builders.py new file mode 100644 index 000000000000..57a66d5c7dec --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/_request_builders.py @@ -0,0 +1,220 @@ +# 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 TYPE_CHECKING + +from azure.core.rest import HttpRequest +from msrest import Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Optional + +_SERIALIZER = Serializer() + + +def build_query_knowledgebase_request( + **kwargs # type: Any +): + # type: (...) -> HttpRequest + """Answers the specified question using your knowledgebase. + + Answers the specified question using your knowledgebase. + + See https://aka.ms/azsdk/python/llcwiki for how to incorporate this request builder into your + code flow. + + :keyword project_name: The name of the project to use. + :paramtype project_name: str + :keyword json: Pass in a JSON-serializable object (usually a dictionary). See the template in + our example to find the input shape. Post body of the request. + :paramtype json: Any + :keyword content: Pass in binary content you want in the body of the request (typically bytes, + a byte iterator, or stream input). Post body of the request. + :paramtype content: Any + :keyword deployment_name: The name of the specific deployment of the project to use. + :paramtype deployment_name: str + :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's + `send_request` method. See https://aka.ms/azsdk/python/protocol/quickstart for how to + incorporate this response into your code flow. + :rtype: ~azure.core.rest.HttpRequest + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your `json` input. + json = { + "answerSpanRequest": { + "confidenceScoreThreshold": "float (optional)", + "enable": "bool (optional)", + "topAnswersWithSpan": "int (optional)" + }, + "confidenceScoreThreshold": "float (optional)", + "context": { + "previousQnaId": "int", + "previousUserQuery": "str (optional)" + }, + "includeUnstructuredSources": "bool (optional)", + "qnaId": "int (optional)", + "question": "str (optional)", + "rankerType": "str (optional)", + "strictFilters": { + "compoundOperation": "str (optional)", + "metadataFilter": { + "compoundOperation": "str (optional)", + "metadata": { + "str": "str (optional)" + } + }, + "sourceFilter": [ + "str (optional)" + ] + }, + "top": "int (optional)", + "userId": "str (optional)" + } + + # response body for status code(s): 200 + response.json() == { + "answers": [ + { + "answer": "str (optional)", + "answerSpan": { + "confidenceScore": "float (optional)", + "length": "int (optional)", + "offset": "int (optional)", + "text": "str (optional)" + }, + "confidenceScore": "float (optional)", + "dialog": { + "isContextOnly": "bool (optional)", + "prompts": [ + { + "displayOrder": "int (optional)", + "displayText": "str (optional)", + "qnaId": "int (optional)" + } + ] + }, + "id": "int (optional)", + "metadata": { + "str": "str (optional)" + }, + "questions": [ + "str (optional)" + ], + "source": "str (optional)" + } + ] + } + """ + + content_type = kwargs.pop("content_type", None) # type: Optional[str] + project_name = kwargs.pop("project_name") # type: str + json = kwargs.pop("json", None) # type: Any + deployment_name = kwargs.pop("deployment_name", None) # type: Optional[str] + + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = kwargs.pop("template_url", "/:query-knowledgebases") + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters["projectName"] = _SERIALIZER.query("project_name", project_name, "str") + if deployment_name is not None: + query_parameters["deploymentName"] = _SERIALIZER.query("deployment_name", deployment_name, "str") + query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=url, params=query_parameters, headers=header_parameters, **kwargs) + + +def build_query_text_request( + **kwargs # type: Any +): + # type: (...) -> HttpRequest + """Answers the specified question using the provided text in the body. + + Answers the specified question using the provided text in the body. + + See https://aka.ms/azsdk/python/llcwiki for how to incorporate this request builder into your + code flow. + + :keyword json: Pass in a JSON-serializable object (usually a dictionary). See the template in + our example to find the input shape. Post body of the request. + :paramtype json: Any + :keyword content: Pass in binary content you want in the body of the request (typically bytes, + a byte iterator, or stream input). Post body of the request. + :paramtype content: Any + :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's + `send_request` method. See https://aka.ms/azsdk/python/protocol/quickstart for how to + incorporate this response into your code flow. + :rtype: ~azure.core.rest.HttpRequest + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your `json` input. + json = { + "language": "str (optional)", + "question": "str", + "records": [ + { + "id": "str", + "text": "str" + } + ], + "stringIndexType": "str (optional). Default value is \"TextElements_v8\"" + } + + # response body for status code(s): 200 + response.json() == { + "answers": [ + { + "answer": "str (optional)", + "answerSpan": { + "confidenceScore": "float (optional)", + "length": "int (optional)", + "offset": "int (optional)", + "text": "str (optional)" + }, + "confidenceScore": "float (optional)", + "id": "str (optional)", + "length": "int (optional)", + "offset": "int (optional)" + } + ] + } + """ + + content_type = kwargs.pop("content_type", None) # type: Optional[str] + json = kwargs.pop("json", None) # type: Any + + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = kwargs.pop("template_url", "/:query-text") + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=url, params=query_parameters, headers=header_parameters, **kwargs) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/_request_builders_py3.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/_request_builders_py3.py new file mode 100644 index 000000000000..2ea1239df3f6 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/rest/_request_builders_py3.py @@ -0,0 +1,212 @@ +# 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, Optional + +from azure.core.rest import HttpRequest +from msrest import Serializer + +_SERIALIZER = Serializer() + + +def build_query_knowledgebase_request( + *, project_name: str, json: Any = None, content: Any = None, deployment_name: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + """Answers the specified question using your knowledgebase. + + Answers the specified question using your knowledgebase. + + See https://aka.ms/azsdk/python/llcwiki for how to incorporate this request builder into your + code flow. + + :keyword project_name: The name of the project to use. + :paramtype project_name: str + :keyword json: Pass in a JSON-serializable object (usually a dictionary). See the template in + our example to find the input shape. Post body of the request. + :paramtype json: Any + :keyword content: Pass in binary content you want in the body of the request (typically bytes, + a byte iterator, or stream input). Post body of the request. + :paramtype content: Any + :keyword deployment_name: The name of the specific deployment of the project to use. + :paramtype deployment_name: str + :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's + `send_request` method. See https://aka.ms/azsdk/python/protocol/quickstart for how to + incorporate this response into your code flow. + :rtype: ~azure.core.rest.HttpRequest + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your `json` input. + json = { + "answerSpanRequest": { + "confidenceScoreThreshold": "float (optional)", + "enable": "bool (optional)", + "topAnswersWithSpan": "int (optional)" + }, + "confidenceScoreThreshold": "float (optional)", + "context": { + "previousQnaId": "int", + "previousUserQuery": "str (optional)" + }, + "includeUnstructuredSources": "bool (optional)", + "qnaId": "int (optional)", + "question": "str (optional)", + "rankerType": "str (optional)", + "strictFilters": { + "compoundOperation": "str (optional)", + "metadataFilter": { + "compoundOperation": "str (optional)", + "metadata": { + "str": "str (optional)" + } + }, + "sourceFilter": [ + "str (optional)" + ] + }, + "top": "int (optional)", + "userId": "str (optional)" + } + + # response body for status code(s): 200 + response.json() == { + "answers": [ + { + "answer": "str (optional)", + "answerSpan": { + "confidenceScore": "float (optional)", + "length": "int (optional)", + "offset": "int (optional)", + "text": "str (optional)" + }, + "confidenceScore": "float (optional)", + "dialog": { + "isContextOnly": "bool (optional)", + "prompts": [ + { + "displayOrder": "int (optional)", + "displayText": "str (optional)", + "qnaId": "int (optional)" + } + ] + }, + "id": "int (optional)", + "metadata": { + "str": "str (optional)" + }, + "questions": [ + "str (optional)" + ], + "source": "str (optional)" + } + ] + } + """ + + content_type = kwargs.pop("content_type", None) # type: Optional[str] + + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = kwargs.pop("template_url", "/:query-knowledgebases") + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters["projectName"] = _SERIALIZER.query("project_name", project_name, "str") + if deployment_name is not None: + query_parameters["deploymentName"] = _SERIALIZER.query("deployment_name", deployment_name, "str") + query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest( + method="POST", url=url, params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs + ) + + +def build_query_text_request(*, json: Any = None, content: Any = None, **kwargs: Any) -> HttpRequest: + """Answers the specified question using the provided text in the body. + + Answers the specified question using the provided text in the body. + + See https://aka.ms/azsdk/python/llcwiki for how to incorporate this request builder into your + code flow. + + :keyword json: Pass in a JSON-serializable object (usually a dictionary). See the template in + our example to find the input shape. Post body of the request. + :paramtype json: Any + :keyword content: Pass in binary content you want in the body of the request (typically bytes, + a byte iterator, or stream input). Post body of the request. + :paramtype content: Any + :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's + `send_request` method. See https://aka.ms/azsdk/python/protocol/quickstart for how to + incorporate this response into your code flow. + :rtype: ~azure.core.rest.HttpRequest + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your `json` input. + json = { + "language": "str (optional)", + "question": "str", + "records": [ + { + "id": "str", + "text": "str" + } + ], + "stringIndexType": "str (optional). Default value is \"TextElements_v8\"" + } + + # response body for status code(s): 200 + response.json() == { + "answers": [ + { + "answer": "str (optional)", + "answerSpan": { + "confidenceScore": "float (optional)", + "length": "int (optional)", + "offset": "int (optional)", + "text": "str (optional)" + }, + "confidenceScore": "float (optional)", + "id": "str (optional)", + "length": "int (optional)", + "offset": "int (optional)" + } + ] + } + """ + + content_type = kwargs.pop("content_type", None) # type: Optional[str] + + api_version = "2021-05-01-preview" + accept = "application/json" + + # Construct URL + url = kwargs.pop("template_url", "/:query-text") + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest( + method="POST", url=url, params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs + ) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/dev_requirements.txt b/sdk/cognitivelanguage/azure-ai-language-questionanswering/dev_requirements.txt new file mode 100644 index 000000000000..4ddce08c734b --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/dev_requirements.txt @@ -0,0 +1,8 @@ +-e ../../../tools/azure-sdk-tools +../../core/azure-core +-e ../../../tools/azure-devtools +-e ../../cognitiveservices/azure-mgmt-cognitiveservices +-e ../../identity/azure-identity +aiohttp>=3.0; python_version >= '3.5' +../../nspkg/azure-ai-nspkg +../../nspkg/azure-ai-language-nspkg diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/README.md b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/README.md new file mode 100644 index 000000000000..ce13a0947d16 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/README.md @@ -0,0 +1,59 @@ +.--- +page_type: sample +languages: + - python +products: +- azure +- azure-cognitive-services +- azure-qna-maker +urlFragment: languagequestionanswering-samples +--- + +# Samples for Language QuestionAnswering client library for Python + +Question Answering is a cloud-based API service that lets you create a conversational question-and-answer layer over your existing data. Use it to build a knowledge base by extracting questions and answers from your semi-structured content, including FAQ, manuals, and documents. Answer users' questions with the best answers from the QnAs in your knowledge base—automatically. Your knowledge base gets smarter, too, as it continually learns from user behavior. + +These code samples show common scenario operations with the Azure Language QuestionAnswering client library. +The async versions of the samples require Python 3.6 or later. +You can authenticate your client with a QuestionAnswering API key. + +These sample programs show common scenarios for the QuestionAnswering client's offerings. + +|**File Name**|**Description**| +|-------------|---------------| +|[sample_query_knowledgebase.py][query_knowledgebase] and [sample_query_knowledgebase_async.py][query_knowledgebase_async]|Ask a question from a knowledgebase| +|[sample_chat.py][chat] and [sample_chat_async.py][chat_async]|Ask a follow-up question (chit-chat)| +|[sample_query_text.py][query_text] and [sample_query_text_async.py][query_text_async]|Ask a question from provided text data| + + +### Prerequisites + +* Python 2.7, or 3.6 or later is required to use this package. +* An [Azure subscription][azure_subscription] +* An existing Question Answering resource + + +## Setup + +1. Install the Azure QuestionAnswering client library for Python with [pip][pip]): +```bash +pip install --pre azure-ai-language-questionanswering +``` +2. Clone or download this sample repository +3. Open the sample folder in Visual Studio Code or your IDE of choice. + +## Running the samples + +1. Open a terminal window and `cd` to the directory that the samples are saved in. +2. Set the environment variables specified in the sample file you wish to run. +3. Follow the usage described in the file, e.g. `python sample_chat.py` + + +[query_knowledgebase]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_knowledgebase.py +[query_knowledgebase_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_knowledgebase_async.py +[chat]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_chat.py +[chat_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_chat_async.py +[query_text]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_text.py +[query_text_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_text_async.py +[pip]: https://pypi.org/project/pip/ +[azure_subscription]: https://azure.microsoft.com/free/ diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_chat_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_chat_async.py new file mode 100644 index 000000000000..014873fcf692 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_chat_async.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +FILE: sample_chat_async.py + +DESCRIPTION: + This sample demonstrates how to ask a follow-up question (chit-chat) from a knowledgebase. + +USAGE: + python sample_chat_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource. + 2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key. + 3) AZURE_QUESTIONANSWERING_PROJECT - the name of a knowledgebase project. +""" + +import asyncio + + +async def sample_chit_chat(): + # [START chit_chat_async] + import os + from azure.core.credentials import AzureKeyCredential + from azure.ai.language.questionanswering.aio import QuestionAnsweringClient + from azure.ai.language.questionanswering import models as qna + + endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"] + key = os.environ["AZURE_QUESTIONANSWERING_KEY"] + knowledgebase_project = os.environ["AZURE_QUESTIONANSWERING_PROJECT"] + + client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key)) + async with client: + first_question = qna.KnowledgebaseQueryParameters( + question="How long should my Surface battery last?", + top=3, + confidence_score_threshold=0.2, + include_unstructured_sources=True, + answer_span_request=qna.AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + ) + + output = await client.query_knowledgebase( + project_name=knowledgebase_project, + knowledgebase_query_parameters=first_question + ) + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(first_question.question)) + print("A: {}".format(best_answer.answer_span.text)) + + followup_question = qna.KnowledgebaseQueryParameters( + question="How long it takes to charge Surface?", + top=3, + confidence_score_threshold=0.2, + context=qna.KnowledgebaseAnswerRequestContext( + previous_user_query="How long should my Surface battery last?", + previous_qna_id=best_answer.id + ), + answer_span_request=qna.AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + include_unstructured_sources=True + ) + + output = await client.query_knowledgebase( + project_name=knowledgebase_project, + knowledgebase_query_parameters=followup_question + ) + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(followup_question.question)) + print("A: {}".format(best_answer.answer_span.text)) + + # [END chit_chat_async] + + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(sample_chit_chat()) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_knowledgebase_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_knowledgebase_async.py new file mode 100644 index 000000000000..21f39fa023b8 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_knowledgebase_async.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +FILE: sample_query_knowledgebase_async.py + +DESCRIPTION: + This sample demonstrates how to ask a question from a knowledgebase. + +USAGE: + python sample_query_knowledgebase_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource. + 2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key. + 3) AZURE_QUESTIONANSWERING_PROJECT - the name of a knowledgebase project. +""" + +import asyncio + + +async def sample_query_knowledgebase(): + # [START query_knowledgebase_async] + import os + from azure.core.credentials import AzureKeyCredential + from azure.ai.language.questionanswering.aio import QuestionAnsweringClient + from azure.ai.language.questionanswering import models as qna + + endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"] + key = os.environ["AZURE_QUESTIONANSWERING_KEY"] + knowledgebase_project = os.environ["AZURE_QUESTIONANSWERING_PROJECT"] + + client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key)) + async with client: + input = qna.KnowledgebaseQueryParameters( + question="How long should my Surface battery last?", + top=3, + confidence_score_threshold=0.2, + include_unstructured_sources=True, + answer_span_request=qna.AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + ) + + output = await client.query_knowledgebase( + project_name=knowledgebase_project, + knowledgebase_query_parameters=input + ) + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(input.question)) + print("A: {}".format(best_answer.answer_span.text)) + + # [END query_knowledgebase_async] + + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(sample_query_knowledgebase()) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_text_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_text_async.py new file mode 100644 index 000000000000..a88fda39ab92 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_text_async.py @@ -0,0 +1,61 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +FILE: sample_query_text_async.py + +DESCRIPTION: + This sample demonstrates how to ask a question from supplied text data. + +USAGE: + python sample_query_text_async.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource. + 2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key. +""" + + +async def sample_query_text(): + # [START query_text_async] + import os + from azure.core.credentials import AzureKeyCredential + from azure.ai.language.questionanswering.aio import QuestionAnsweringClient + from azure.ai.language.questionanswering import models as qna + + endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"] + key = os.environ["AZURE_QUESTIONANSWERING_KEY"] + + client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key)) + async with client: + input = qna.TextQueryParameters( + question="How long it takes to charge surface?", + records=[ + qna.TextInput( + text="Power and charging. It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. " + + "It can take longer if you’re using your Surface for power-intensive activities like gaming or video streaming while you’re charging it.", + id="doc1" + ), + qna.TextInput( + text="You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. " + + "The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface.", + id="doc2" + ) + ] + ) + + output = await client.query_text(input) + + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(input.question)) + print("A: {}".format(best_answer.answer)) + + # [END query_text_async] + + +if __name__ == '__main__': + loop = asyncio.get_event_loop() + loop.run_until_complete(sample_query_text()) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_chat.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_chat.py new file mode 100644 index 000000000000..8ccc882c353a --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_chat.py @@ -0,0 +1,84 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +FILE: sample_chat.py + +DESCRIPTION: + This sample demonstrates how to ask a follow-up question (chit-chat) from a knowledgebase. + +USAGE: + python sample_chat.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource. + 2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key. + 3) AZURE_QUESTIONANSWERING_PROJECT - the name of a knowledgebase project. +""" + + +def sample_chit_chat(): + # [START chit_chat] + import os + from azure.core.credentials import AzureKeyCredential + from azure.ai.language.questionanswering import QuestionAnsweringClient + from azure.ai.language.questionanswering import models as qna + + endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"] + key = os.environ["AZURE_QUESTIONANSWERING_KEY"] + knowledgebase_project = os.environ["AZURE_QUESTIONANSWERING_PROJECT"] + + client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key)) + with client: + first_question = qna.KnowledgebaseQueryParameters( + question="How long should my Surface battery last?", + top=3, + confidence_score_threshold=0.2, + include_unstructured_sources=True, + answer_span_request=qna.AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + ) + + output = client.query_knowledgebase( + project_name=knowledgebase_project, + knowledgebase_query_parameters=first_question + ) + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(first_question.question)) + print("A: {}".format(best_answer.answer_span.text)) + + followup_question = qna.KnowledgebaseQueryParameters( + question="How long it takes to charge Surface?", + top=3, + confidence_score_threshold=0.2, + context=qna.KnowledgebaseAnswerRequestContext( + previous_user_query="How long should my Surface battery last?", + previous_qna_id=best_answer.id + ), + answer_span_request=qna.AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + include_unstructured_sources=True + ) + + output = client.query_knowledgebase( + project_name=knowledgebase_project, + knowledgebase_query_parameters=followup_question + ) + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(followup_question.question)) + print("A: {}".format(best_answer.answer_span.text)) + + # [END chit_chat] + + +if __name__ == '__main__': + sample_chit_chat() \ No newline at end of file diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_knowledgebase.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_knowledgebase.py new file mode 100644 index 000000000000..ef1f4969eb6b --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_knowledgebase.py @@ -0,0 +1,60 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +FILE: sample_query_knowledgebase.py + +DESCRIPTION: + This sample demonstrates how to ask a question from a knowledgebase. + +USAGE: + python sample_query_knowledgebase.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource. + 2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key. + 3) AZURE_QUESTIONANSWERING_PROJECT - the name of a knowledgebase project. +""" + + +def sample_query_knowledgebase(): + # [START query_knowledgebase] + import os + from azure.core.credentials import AzureKeyCredential + from azure.ai.language.questionanswering import QuestionAnsweringClient + from azure.ai.language.questionanswering import models as qna + + endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"] + key = os.environ["AZURE_QUESTIONANSWERING_KEY"] + knowledgebase_project = os.environ["AZURE_QUESTIONANSWERING_PROJECT"] + + client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key)) + with client: + input = qna.KnowledgebaseQueryParameters( + question="How long should my Surface battery last?", + top=3, + confidence_score_threshold=0.2, + include_unstructured_sources=True, + answer_span_request=qna.AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + ) + + output = client.query_knowledgebase( + project_name=knowledgebase_project, + knowledgebase_query_parameters=input + ) + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(input.question)) + print("A: {}".format(best_answer.answer_span.text)) + + # [END query_knowledgebase] + + +if __name__ == '__main__': + sample_query_knowledgebase() diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_text.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_text.py new file mode 100644 index 000000000000..d18ffa620f0a --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_text.py @@ -0,0 +1,60 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +""" +FILE: sample_query_text.py + +DESCRIPTION: + This sample demonstrates how to ask a question from supplied text data. + +USAGE: + python sample_query_text.py + + Set the environment variables with your own values before running the sample: + 1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource. + 2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key. +""" + + +def sample_query_text(): + # [START query_text] + import os + from azure.core.credentials import AzureKeyCredential + from azure.ai.language.questionanswering import QuestionAnsweringClient + from azure.ai.language.questionanswering import models as qna + + endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"] + key = os.environ["AZURE_QUESTIONANSWERING_KEY"] + + client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key)) + with client: + input = qna.TextQueryParameters( + question="How long it takes to charge surface?", + records=[ + qna.TextInput( + text="Power and charging. It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. " + + "It can take longer if you’re using your Surface for power-intensive activities like gaming or video streaming while you’re charging it.", + id="doc1" + ), + qna.TextInput( + text="You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. " + + "The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface.", + id="doc2" + ) + ] + ) + + output = client.query_text(input) + + best_answer = [a for a in output.answers if a.confidence_score > 0.9][0] + print("Q: {}".format(input.question)) + print("A: {}".format(best_answer.answer)) + + # [END query_text] + + +if __name__ == '__main__': + sample_query_text() diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/sdk_packaging.toml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/sdk_packaging.toml new file mode 100644 index 000000000000..901bc8ccbfa6 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/sdk_packaging.toml @@ -0,0 +1,2 @@ +[packaging] +auto_update = false diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/setup.cfg b/sdk/cognitivelanguage/azure-ai-language-questionanswering/setup.cfg new file mode 100644 index 000000000000..3c6e79cf31da --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal=1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/setup.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/setup.py new file mode 100644 index 000000000000..ff44705781b0 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/setup.py @@ -0,0 +1,80 @@ +from setuptools import setup, find_packages +import os +from io import open +import re + +# example setup.py Feel free to copy the entire "azure-template" folder into a package folder named +# with "azure-". Ensure that the below arguments to setup() are updated to reflect +# your package. + +# this setup.py is set up in a specific way to keep the azure* and azure-mgmt-* namespaces WORKING all the way +# up from python 2.7. Reference here: https://github.com/Azure/azure-sdk-for-python/wiki/Azure-packaging + +PACKAGE_NAME = "azure-ai-language-questionanswering" +PACKAGE_PPRINT_NAME = "Question Answering" + +# a-b-c => a/b/c +package_folder_path = PACKAGE_NAME.replace('-', '/') +# a-b-c => a.b.c +namespace_name = PACKAGE_NAME.replace('-', '.') + +# Version extraction inspired from 'requests' +with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', + fd.read(), re.MULTILINE).group(1) +if not version: + raise RuntimeError('Cannot find version information') + +with open('README.md', encoding='utf-8') as f: + long_description = f.read() + +setup( + name=PACKAGE_NAME, + version=version, + description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), + + # ensure that these are updated to reflect the package owners' information + long_description=long_description, + long_description_content_type='text/markdown', + url='https://github.com/Azure/azure-sdk-for-python', + author='Microsoft Corporation', + author_email='azuresdkengsysadmins@microsoft.com', + + license='MIT License', + # ensure that the development status reflects the status of your package + classifiers=[ + "Development Status :: 4 - Beta", + + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'License :: OSI Approved :: MIT License', + ], + packages=find_packages(exclude=[ + 'tests', + # Exclude packages that will be covered by PEP420 or nspkg + # This means any folder structure that only consists of a __init__.py. + # For example, for storage, this would mean adding 'azure.storage' + # in addition to the default 'azure' that is seen here. + 'azure' + 'azure.ai', + 'azure.ai.language', + ]), + install_requires=[ + 'azure-core<2.0.0,>=1.16.0', + "msrest>=0.6.21" + ], + extras_require={ + ":python_version<'3.0'": ['futures', 'azure-ai-language-nspkg'], + ":python_version<'3.5'": ["typing"] + }, + project_urls={ + 'Bug Reports': 'https://github.com/Azure/azure-sdk-for-python/issues', + 'Source': 'https://github.com/Azure/azure-sdk-python', + } +) diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/asynctestcase.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/asynctestcase.py new file mode 100644 index 000000000000..8893eeede181 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/asynctestcase.py @@ -0,0 +1,38 @@ +# 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. +# -------------------------------------------------------------------------- +import asyncio +import functools +from azure_devtools.scenario_tests.utilities import trim_kwargs_from_test_function +from azure.core.credentials import AccessToken +from testcase import QuestionAnsweringTest + + +class AsyncFakeTokenCredential(object): + """Protocol for classes able to provide OAuth tokens. + :param str scopes: Lets you specify the type of access needed. + """ + def __init__(self): + self.token = AccessToken("YOU SHALL NOT PASS", 0) + + async def get_token(self, *args): + return self.token + + +class AsyncQuestionAnsweringTest(QuestionAnsweringTest): + + def generate_oauth_token(self): + if self.is_live: + from azure.identity.aio import ClientSecretCredential + return ClientSecretCredential( + self.get_settings_value("TENANT_ID"), + self.get_settings_value("CLIENT_ID"), + self.get_settings_value("CLIENT_SECRET"), + ) + return self.generate_fake_token() + + def generate_fake_token(self): + return AsyncFakeTokenCredential() diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/conftest.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/conftest.py new file mode 100644 index 000000000000..bdc8e3478396 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/conftest.py @@ -0,0 +1,15 @@ +# 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. +# -------------------------------------------------------------------------- + +import sys + + +# Ignore async tests for Python < 3.5 +collect_ignore_glob = [] +if sys.version_info < (3, 5): + collect_ignore_glob.append("*_async.py") + diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase.yaml new file mode 100644 index 000000000000..e45e18a420ba --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase.yaml @@ -0,0 +1,124 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousQnaId": + 4, "previousUserQuery": "Meet Surface Pro 4"}}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '122' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n }\n + \ },\n {\n \"questions\": [\n \"Connect monitors, accessories, + and other devices\"\n ],\n \"answer\": \"**Connect monitors, accessories, + and other devices**\\n\\nYou can connect monitors, accessories, and other + devices directly to your Surface Pro 4 using the USB port, Mini DisplayPort, + or Bluetooth. Or, connect everything to a Surface Dock (sold separately). + With Surface Dock, you can switch between fully connected and fully mobile + with a single connector.\",\n \"confidenceScore\": 46.59,\n \"id\": + 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"connect monitors, accessories, and + other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ }\n },\n {\n \"questions\": [\n \"Projector or monitor.\"\n + \ ],\n \"answer\": \"If your monitor has a DisplayPort, you can connect + it to your Surface using a DisplayPort to Mini DisplayPort cable (sold separately). + If your monitor doesn\u2019t have a DisplayPort or HDMI port, use a VGA cable + and the Mini DisplayPort to VGA Adapter.\\n\\nNote: A VGA adapter or cable + is for video only. Audio will play from your Surface speakers unless you\u2019ve + connected external speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: + - c8be2440-5d35-438e-9302-7438d5285739 + content-length: + - '7123' + content-type: + - application/json; charset=utf-8 + date: + - Fri, 25 Jun 2021 19:41:10 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '1290' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_llc.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_llc.yaml new file mode 100644 index 000000000000..0a59e7267dd4 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_llc.yaml @@ -0,0 +1,124 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousUserQuery": + "Meet Surface Pro 4", "previousQnAId": 4}}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '122' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n }\n + \ },\n {\n \"questions\": [\n \"Connect monitors, accessories, + and other devices\"\n ],\n \"answer\": \"**Connect monitors, accessories, + and other devices**\\n\\nYou can connect monitors, accessories, and other + devices directly to your Surface Pro 4 using the USB port, Mini DisplayPort, + or Bluetooth. Or, connect everything to a Surface Dock (sold separately). + With Surface Dock, you can switch between fully connected and fully mobile + with a single connector.\",\n \"confidenceScore\": 46.59,\n \"id\": + 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"connect monitors, accessories, and + other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ }\n },\n {\n \"questions\": [\n \"Projector or monitor.\"\n + \ ],\n \"answer\": \"If your monitor has a DisplayPort, you can connect + it to your Surface using a DisplayPort to Mini DisplayPort cable (sold separately). + If your monitor doesn\u2019t have a DisplayPort or HDMI port, use a VGA cable + and the Mini DisplayPort to VGA Adapter.\\n\\nNote: A VGA adapter or cable + is for video only. Audio will play from your Surface speakers unless you\u2019ve + connected external speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: + - 9cb8b0fb-c798-439e-b03e-54abed982534 + content-length: + - '7123' + content-type: + - application/json; charset=utf-8 + date: + - Fri, 25 Jun 2021 19:41:11 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '1223' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_llc_with_answerspan.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_llc_with_answerspan.yaml new file mode 100644 index 000000000000..bf86e56c48e1 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_llc_with_answerspan.yaml @@ -0,0 +1,129 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousUserQuery": + "Meet Surface Pro 4", "previousQnAId": 4}, "answerSpanRequest": {"enable": true, + "confidenceScoreThreshold": 0.1, "topAnswersWithSpan": 1}}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '219' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n },\n + \ \"answerSpan\": {\n \"text\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone.\",\n \"confidenceScore\": 1.06,\n \"offset\": + 0,\n \"length\": 206\n }\n },\n {\n \"questions\": + [\n \"Connect monitors, accessories, and other devices\"\n ],\n + \ \"answer\": \"**Connect monitors, accessories, and other devices**\\n\\nYou + can connect monitors, accessories, and other devices directly to your Surface + Pro 4 using the USB port, Mini DisplayPort, or Bluetooth. Or, connect everything + to a Surface Dock (sold separately). With Surface Dock, you can switch between + fully connected and fully mobile with a single connector.\",\n \"confidenceScore\": + 46.59,\n \"id\": 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"connect monitors, + accessories, and other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ }\n },\n {\n \"questions\": [\n \"Projector or monitor.\"\n + \ ],\n \"answer\": \"If your monitor has a DisplayPort, you can connect + it to your Surface using a DisplayPort to Mini DisplayPort cable (sold separately). + If your monitor doesn\u2019t have a DisplayPort or HDMI port, use a VGA cable + and the Mini DisplayPort to VGA Adapter.\\n\\nNote: A VGA adapter or cable + is for video only. Audio will play from your Surface speakers unless you\u2019ve + connected external speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: + - 2eb92f74-cda1-4bdb-a18f-a59b4d7cdf11 + content-length: + - '7459' + content-type: + - application/json; charset=utf-8 + date: + - Fri, 25 Jun 2021 19:41:13 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '426' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_only_id.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_only_id.yaml new file mode 100644 index 000000000000..a95cc66455f2 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_only_id.yaml @@ -0,0 +1,48 @@ +interactions: +- request: + body: '{"qnaId": 19}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '13' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Charge + your Surface Pro 4\"\n ],\n \"answer\": \"**Charge your Surface + Pro 4**\\n\\n1. Connect the two parts of the power cord.\\n\\n2. Connect + the power cord securely to the charging port.\\n\\n3. Plug the power supply + into an electrical outlet.\",\n \"confidenceScore\": 1.0,\n \"id\": + 19,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"charge your surface pro 4\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: + - 2d116c69-e644-4b11-b005-0d4d5cd13bbc + content-length: + - '583' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 30 Jun 2021 15:15:46 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '223' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_answerspan.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_answerspan.yaml new file mode 100644 index 000000000000..3b4ba3a32f81 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_answerspan.yaml @@ -0,0 +1,134 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousQnaId": + 4, "previousUserQuery": "Meet Surface Pro 4"}, "answerSpanRequest": {"enable": + true, "confidenceScoreThreshold": 0.1, "topAnswersWithSpan": 2}}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '219' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n },\n + \ \"answerSpan\": {\n \"text\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone.\",\n \"confidenceScore\": 1.06,\n \"offset\": + 0,\n \"length\": 206\n }\n },\n {\n \"questions\": + [\n \"Connect monitors, accessories, and other devices\"\n ],\n + \ \"answer\": \"**Connect monitors, accessories, and other devices**\\n\\nYou + can connect monitors, accessories, and other devices directly to your Surface + Pro 4 using the USB port, Mini DisplayPort, or Bluetooth. Or, connect everything + to a Surface Dock (sold separately). With Surface Dock, you can switch between + fully connected and fully mobile with a single connector.\",\n \"confidenceScore\": + 46.59,\n \"id\": 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"connect monitors, + accessories, and other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ },\n \"answerSpan\": {\n \"text\": \"**Connect monitors, + accessories, and other devices**\\n\\nYou can connect monitors, accessories, + and other devices directly to your Surface Pro 4 using the USB port, Mini + DisplayPort, or Bluetooth.\",\n \"confidenceScore\": 6.97,\n \"offset\": + 0,\n \"length\": 194\n }\n },\n {\n \"questions\": + [\n \"Projector or monitor.\"\n ],\n \"answer\": \"If your + monitor has a DisplayPort, you can connect it to your Surface using a DisplayPort + to Mini DisplayPort cable (sold separately). If your monitor doesn\u2019t + have a DisplayPort or HDMI port, use a VGA cable and the Mini DisplayPort + to VGA Adapter.\\n\\nNote: A VGA adapter or cable is for video only. Audio + will play from your Surface speakers unless you\u2019ve connected external + speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: + - e9f17bfa-0949-4d3b-90a2-cc77348ec62a + content-length: + - '7781' + content-type: + - application/json; charset=utf-8 + date: + - Fri, 25 Jun 2021 19:41:13 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '346' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_dictparams.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_dictparams.yaml new file mode 100644 index 000000000000..a7fcb080edda --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_dictparams.yaml @@ -0,0 +1,64 @@ +interactions: +- request: + body: '{"question": "How long should my Surface battery last?", "top": 3, "userId": + "sd53lsY=", "confidenceScoreThreshold": 0.2, "answerSpanRequest": {"enable": + true, "confidenceScoreThreshold": 0.2, "topAnswersWithSpan": 1}, "includeUnstructuredSources": + true}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '254' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Make + your battery last\"\n ],\n \"answer\": \"**Make your battery last**\\n\\nFor + info on how to care for your battery and power supply, conserve power, and + make your Surface battery last longer, see [Surface battery and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\",\n \"confidenceScore\": 0.9292,\n \"id\": 27,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"make your battery last\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n },\n {\n \"questions\": [\n \"Check the battery + level\"\n ],\n \"answer\": \"**Check the battery level**\\n\\nYou + can check the battery level from the lock screen or the desktop:\",\n \"confidenceScore\": + 0.3583,\n \"id\": 24,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"check the battery + level\"\n },\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": []\n }\n },\n {\n \"questions\": [\n + \ \"Desktop taskbar.\"\n ],\n \"answer\": \"**Desktop taskbar.**\\n\\nBattery + status appears at the right side of the taskbar. Select the battery icon for + info about the charging and battery status, including the percent remaining. + \u272A\",\n \"confidenceScore\": 0.2229,\n \"id\": 26,\n \"source\": + \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": {},\n \"dialog\": + {\n \"isContextOnly\": false,\n \"prompts\": []\n }\n }\n + \ ]\n}" + headers: + apim-request-id: + - 967bb864-5081-4f3e-9b98-c3861626ed3f + content-length: + - '1609' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 30 Jun 2021 15:36:56 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '1397' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_followup.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_followup.yaml new file mode 100644 index 000000000000..184ac4a01b84 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase.test_query_knowledgebase_with_followup.yaml @@ -0,0 +1,135 @@ +interactions: +- request: + body: '{"question": "How long should my Surface battery last?", "top": 3, "userId": + "sd53lsY=", "confidenceScoreThreshold": 0.2, "answerSpanRequest": {"enable": + true, "confidenceScoreThreshold": 0.2, "topAnswersWithSpan": 1}, "includeUnstructuredSources": + true}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '254' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Make + your battery last\"\n ],\n \"answer\": \"**Make your battery last**\\n\\nFor + info on how to care for your battery and power supply, conserve power, and + make your Surface battery last longer, see [Surface battery and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\",\n \"confidenceScore\": 0.9292,\n \"id\": 27,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"make your battery last\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n },\n {\n \"questions\": [\n \"Check the battery + level\"\n ],\n \"answer\": \"**Check the battery level**\\n\\nYou + can check the battery level from the lock screen or the desktop:\",\n \"confidenceScore\": + 0.3583,\n \"id\": 24,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"check the battery + level\"\n },\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": []\n }\n },\n {\n \"questions\": [\n + \ \"Desktop taskbar.\"\n ],\n \"answer\": \"**Desktop taskbar.**\\n\\nBattery + status appears at the right side of the taskbar. Select the battery icon for + info about the charging and battery status, including the percent remaining. + \u272A\",\n \"confidenceScore\": 0.2229,\n \"id\": 26,\n \"source\": + \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": {},\n \"dialog\": + {\n \"isContextOnly\": false,\n \"prompts\": []\n }\n }\n + \ ]\n}" + headers: + apim-request-id: + - 7e3a11a9-79ea-41fc-8963-db475c64f5af + content-length: + - '1609' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 30 Jun 2021 15:14:31 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '1075' + status: + code: 200 + message: OK +- request: + body: '{"question": "How long it takes to charge Surface?", "top": 3, "userId": + "sd53lsY=", "confidenceScoreThreshold": 0.2, "context": {"previousQnaId": 27, + "previousUserQuery": "How long should my Surface battery last?"}, "answerSpanRequest": + {"enable": true, "confidenceScoreThreshold": 0.2, "topAnswersWithSpan": 1}, + "includeUnstructuredSources": true}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '349' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Power + and charging\"\n ],\n \"answer\": \"**Power and charging**\\n\\nIt + takes two to four hours to charge the Surface Pro 4 battery fully from an + empty state. It can take longer if you\u2019re using your Surface for power-intensive + activities like gaming or video streaming while you\u2019re charging it.\\n\\nYou + can use the USB port on your Surface Pro 4 power supply to charge other devices, + like a phone, while your Surface charges. The USB port on the power supply + is only for charging, not for data transfer. If you want to use a USB device, + plug it into the USB port on your Surface.\",\n \"confidenceScore\": + 0.6545000000000001,\n \"id\": 23,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"power and charging\"\n + \ },\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + [\n {\n \"displayOrder\": 0,\n \"qnaId\": 24,\n + \ \"displayText\": \"Check the battery level\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 25,\n \"displayText\": + \"Lock screen.\"\n },\n {\n \"displayOrder\": + 2,\n \"qnaId\": 26,\n \"displayText\": \"Desktop taskbar.\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 27,\n \"displayText\": \"Make your battery last\"\n }\n + \ ]\n },\n \"answerSpan\": {\n \"text\": \"two to four + hours\",\n \"confidenceScore\": 30.86,\n \"offset\": 33,\n \"length\": + 18\n }\n },\n {\n \"questions\": [\n \"Charge your + Surface Pro 4\"\n ],\n \"answer\": \"**Charge your Surface Pro 4**\\n\\n1. + \ Connect the two parts of the power cord.\\n\\n2. Connect the power cord + securely to the charging port.\\n\\n3. Plug the power supply into an electrical + outlet.\",\n \"confidenceScore\": 0.31989999999999996,\n \"id\": + 19,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"charge your surface pro 4\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: + - 94119467-33a8-4222-b270-0deb60b671eb + content-length: + - '2177' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 30 Jun 2021 15:14:31 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '867' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase.yaml new file mode 100644 index 000000000000..303f9048d446 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase.yaml @@ -0,0 +1,114 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousQnaId": + 4, "previousUserQuery": "Meet Surface Pro 4"}}' + headers: + Accept: + - application/json + Content-Length: + - '122' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n }\n + \ },\n {\n \"questions\": [\n \"Connect monitors, accessories, + and other devices\"\n ],\n \"answer\": \"**Connect monitors, accessories, + and other devices**\\n\\nYou can connect monitors, accessories, and other + devices directly to your Surface Pro 4 using the USB port, Mini DisplayPort, + or Bluetooth. Or, connect everything to a Surface Dock (sold separately). + With Surface Dock, you can switch between fully connected and fully mobile + with a single connector.\",\n \"confidenceScore\": 46.59,\n \"id\": + 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"connect monitors, accessories, and + other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ }\n },\n {\n \"questions\": [\n \"Projector or monitor.\"\n + \ ],\n \"answer\": \"If your monitor has a DisplayPort, you can connect + it to your Surface using a DisplayPort to Mini DisplayPort cable (sold separately). + If your monitor doesn\u2019t have a DisplayPort or HDMI port, use a VGA cable + and the Mini DisplayPort to VGA Adapter.\\n\\nNote: A VGA adapter or cable + is for video only. Audio will play from your Surface speakers unless you\u2019ve + connected external speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: 6ac46b21-848e-4ba3-9bee-57780f0a6f97 + content-length: '7123' + content-type: application/json; charset=utf-8 + date: Fri, 25 Jun 2021 19:41:14 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '267' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_bad_request.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_bad_request.yaml new file mode 100644 index 000000000000..af9de17280ea --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_bad_request.yaml @@ -0,0 +1,33 @@ +interactions: +- request: + body: '{"qna_id": 19}' + headers: + Accept: + - application/json + Content-Length: + - '14' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"error\": {\n \"code\": \"BadArgument\",\n \"message\": + \"Invalid input. See details.\",\n \"details\": [\n {\n \"code\": + \"ValidationFailure\",\n \"message\": \"'Question' must not be empty.\",\n + \ \"target\": \"Question\"\n }\n ]\n }\n}" + headers: + apim-request-id: 984a747d-795f-4205-bc2e-d2a799efb4ff + content-length: '250' + content-type: application/json; charset=utf-8 + date: Wed, 30 Jun 2021 18:12:33 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '12' + status: + code: 400 + message: Bad Request + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_llc.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_llc.yaml new file mode 100644 index 000000000000..7358da834cbe --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_llc.yaml @@ -0,0 +1,114 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousUserQuery": + "Meet Surface Pro 4", "previousQnAId": 4}}' + headers: + Accept: + - application/json + Content-Length: + - '122' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n }\n + \ },\n {\n \"questions\": [\n \"Connect monitors, accessories, + and other devices\"\n ],\n \"answer\": \"**Connect monitors, accessories, + and other devices**\\n\\nYou can connect monitors, accessories, and other + devices directly to your Surface Pro 4 using the USB port, Mini DisplayPort, + or Bluetooth. Or, connect everything to a Surface Dock (sold separately). + With Surface Dock, you can switch between fully connected and fully mobile + with a single connector.\",\n \"confidenceScore\": 46.59,\n \"id\": + 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"connect monitors, accessories, and + other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ }\n },\n {\n \"questions\": [\n \"Projector or monitor.\"\n + \ ],\n \"answer\": \"If your monitor has a DisplayPort, you can connect + it to your Surface using a DisplayPort to Mini DisplayPort cable (sold separately). + If your monitor doesn\u2019t have a DisplayPort or HDMI port, use a VGA cable + and the Mini DisplayPort to VGA Adapter.\\n\\nNote: A VGA adapter or cable + is for video only. Audio will play from your Surface speakers unless you\u2019ve + connected external speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: 2cd167a8-d3e3-4d78-974e-616149e71052 + content-length: '7123' + content-type: application/json; charset=utf-8 + date: Fri, 25 Jun 2021 19:41:15 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '252' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_llc_with_answerspan.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_llc_with_answerspan.yaml new file mode 100644 index 000000000000..f7d93b4a9d2d --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_llc_with_answerspan.yaml @@ -0,0 +1,124 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousUserQuery": + "Meet Surface Pro 4", "previousQnAId": 4}, "answerSpanRequest": {"enable": true, + "confidenceScoreThreshold": 0.1, "topAnswersWithSpan": 2}}' + headers: + Accept: + - application/json + Content-Length: + - '219' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n },\n + \ \"answerSpan\": {\n \"text\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone.\",\n \"confidenceScore\": 1.06,\n \"offset\": + 0,\n \"length\": 206\n }\n },\n {\n \"questions\": + [\n \"Connect monitors, accessories, and other devices\"\n ],\n + \ \"answer\": \"**Connect monitors, accessories, and other devices**\\n\\nYou + can connect monitors, accessories, and other devices directly to your Surface + Pro 4 using the USB port, Mini DisplayPort, or Bluetooth. Or, connect everything + to a Surface Dock (sold separately). With Surface Dock, you can switch between + fully connected and fully mobile with a single connector.\",\n \"confidenceScore\": + 46.59,\n \"id\": 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"connect monitors, + accessories, and other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ },\n \"answerSpan\": {\n \"text\": \"**Connect monitors, + accessories, and other devices**\\n\\nYou can connect monitors, accessories, + and other devices directly to your Surface Pro 4 using the USB port, Mini + DisplayPort, or Bluetooth.\",\n \"confidenceScore\": 6.97,\n \"offset\": + 0,\n \"length\": 194\n }\n },\n {\n \"questions\": + [\n \"Projector or monitor.\"\n ],\n \"answer\": \"If your + monitor has a DisplayPort, you can connect it to your Surface using a DisplayPort + to Mini DisplayPort cable (sold separately). If your monitor doesn\u2019t + have a DisplayPort or HDMI port, use a VGA cable and the Mini DisplayPort + to VGA Adapter.\\n\\nNote: A VGA adapter or cable is for video only. Audio + will play from your Surface speakers unless you\u2019ve connected external + speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: f0f3fc36-d981-4b26-a366-e77ba518a1bb + content-length: '7781' + content-type: application/json; charset=utf-8 + date: Fri, 25 Jun 2021 19:41:16 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '388' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_only_id.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_only_id.yaml new file mode 100644 index 000000000000..397adfac6cea --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_only_id.yaml @@ -0,0 +1,38 @@ +interactions: +- request: + body: '{"qnaId": 19}' + headers: + Accept: + - application/json + Content-Length: + - '13' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Charge + your Surface Pro 4\"\n ],\n \"answer\": \"**Charge your Surface + Pro 4**\\n\\n1. Connect the two parts of the power cord.\\n\\n2. Connect + the power cord securely to the charging port.\\n\\n3. Plug the power supply + into an electrical outlet.\",\n \"confidenceScore\": 1.0,\n \"id\": + 19,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"charge your surface pro 4\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: 82923f05-3c9f-416f-9855-2fbefa6085dc + content-length: '583' + content-type: application/json; charset=utf-8 + date: Wed, 30 Jun 2021 15:15:47 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '132' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_answerspan.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_answerspan.yaml new file mode 100644 index 000000000000..453c320799f8 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_answerspan.yaml @@ -0,0 +1,124 @@ +interactions: +- request: + body: '{"question": "Ports and connectors", "top": 3, "context": {"previousQnaId": + 4, "previousUserQuery": "Meet Surface Pro 4"}, "answerSpanRequest": {"enable": + true, "confidenceScoreThreshold": 0.1, "topAnswersWithSpan": 2}}' + headers: + Accept: + - application/json + Content-Length: + - '219' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Ports + and connectors\"\n ],\n \"answer\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone. For more info, see [Connect a USB mouse,](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + [printer, and more](http://www.microsoft.com/surface/support/hardware-and-drivers/connect-a-usb-phone-camera-mouse-and-more) + on Surface.com.\\n\\nSurface Connect When your battery is low, attach the + included power supply to the Surface Connect charging port. For more info, + see [Surface battery](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + [and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\\n\\nIf you use the Surface Dock (sold separately), you connect + your Surface to the dock through the Surface Connect charging and docking + connector to transmit power and data. For more info, see [Using Surface Dock](http://www.microsoft.com/surface/support/hardware-and-drivers/docking-station-surface-dock) + on Surface.com.\\n\\nMicroSD card slot Use the microSD card slot and a microSD + card (sold separately) for file transfer and extra storage. For more info, + see [Surface storage](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + [options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com.\\n\\nMini DisplayPort version 1.2 Share what\u2019s on your + Surface screen by connecting it to an HDTV, monitor, or projector. (Video + adapters are sold separately.) For more info, see [Connect Surface to a TV, + monitor, or projector](https://www.microsoft.com/surface/support/music-photos-and-video/connect-surface-to-a-tv-display-or-projector) + on Surface.com.\\n\\n3.5 mm headset jack Plug in your favorite headset for + a little more privacy when listening to music or conference calls. For more + info, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\\n\\nCover connectors Click in the thin, light, Type Cover + for Surface Pro 4 (sold separately) so you\u2019ll always have a keyboard + when you\u2019re on the go. For more info, see [Type Cover](http://www.microsoft.com/surface/support/hardware-and-drivers/type-cover) + on Surface.com.\\n\\n| Software | Windows 10 Pro operating system Windows + 10 provides new features and many options for entertainment and productivity + at school, at home, or while you\u2019re on the go. To learn more about Windows, + see [Get started with Windows 10](http://windows.microsoft.com/en-us/windows-10/getstarted-whatsnew-cortana) + on Windows.com. Apps You can use the built-in apps featured on your Start + menu and install more apps from the Windows Store. To learn more, see [All + about](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + [apps and get more apps](http://www.microsoft.com/surface/support/apps-and-windows-store/all-about-apps) + on Surface.com. You can also install and use all your favorite desktop apps + on your Surface Pro 4. For more info, see [Install and uninstall apps on Surface](http://www.microsoft.com/surface/support/apps-and-windows-store/install-apps-and-programs) + on Surface.com. |\\n| --- | --- |\\n| Processor | The 6th-generation Intel + Core processor provides speed and power for smooth, fast performance. |\\n| + Memory and storage | Surface Pro 4 is available in configurations with up + to 16 GB of RAM and 512 GB storage. See [Surface storage](http://www.microsoft.com/surface/support/storage) + [on Surface.com](http://www.microsoft.com/surface/support/storage) for info + on available disk space. To learn about additional storage options for Surface + Pro 4, see [Surface storage options](http://www.microsoft.com/surface/support/storage-files-and-folders/surface-storage-options) + on Surface.com. |\\n| Sensors | Six sensors\u2014 accelerometer, magnetometer, + gyro, ambient light sensor, Hall effect, Wi-Fi SAR\u2014let apps do things + like track motion and determine location. |\",\n \"confidenceScore\": + 100.0,\n \"id\": 5,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {},\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": [\n {\n \"displayOrder\": 0,\n \"qnaId\": + 6,\n \"displayText\": \"Software\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 7,\n \"displayText\": + \"Processor\"\n },\n {\n \"displayOrder\": 2,\n + \ \"qnaId\": 8,\n \"displayText\": \"Memory and storage\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 9,\n \"displayText\": \"Sensors\"\n }\n ]\n },\n + \ \"answerSpan\": {\n \"text\": \"**Ports and connectors**\\n\\nSurface + Pro 4 has the ports you expect in a full-feature laptop.\\n\\nFull-size USB + 3.0 port Connect a USB accessory like a mouse, printer, Ethernet adapter, + USB drive, or smartphone.\",\n \"confidenceScore\": 1.06,\n \"offset\": + 0,\n \"length\": 206\n }\n },\n {\n \"questions\": + [\n \"Connect monitors, accessories, and other devices\"\n ],\n + \ \"answer\": \"**Connect monitors, accessories, and other devices**\\n\\nYou + can connect monitors, accessories, and other devices directly to your Surface + Pro 4 using the USB port, Mini DisplayPort, or Bluetooth. Or, connect everything + to a Surface Dock (sold separately). With Surface Dock, you can switch between + fully connected and fully mobile with a single connector.\",\n \"confidenceScore\": + 46.59,\n \"id\": 64,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"connect monitors, + accessories, and other devices\"\n },\n \"dialog\": {\n \"isContextOnly\": + false,\n \"prompts\": [\n {\n \"displayOrder\": + 0,\n \"qnaId\": 65,\n \"displayText\": \"Set up your + workspace with Surface Dock\"\n },\n {\n \"displayOrder\": + 1,\n \"qnaId\": 66,\n \"displayText\": \"Connect or + project to a monitor, screen, or other display\"\n }\n ]\n + \ },\n \"answerSpan\": {\n \"text\": \"**Connect monitors, + accessories, and other devices**\\n\\nYou can connect monitors, accessories, + and other devices directly to your Surface Pro 4 using the USB port, Mini + DisplayPort, or Bluetooth.\",\n \"confidenceScore\": 6.97,\n \"offset\": + 0,\n \"length\": 194\n }\n },\n {\n \"questions\": + [\n \"Projector or monitor.\"\n ],\n \"answer\": \"If your + monitor has a DisplayPort, you can connect it to your Surface using a DisplayPort + to Mini DisplayPort cable (sold separately). If your monitor doesn\u2019t + have a DisplayPort or HDMI port, use a VGA cable and the Mini DisplayPort + to VGA Adapter.\\n\\nNote: A VGA adapter or cable is for video only. Audio + will play from your Surface speakers unless you\u2019ve connected external + speakers. For more info about this, see [Surface sound,](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + [volume, and audio accessories](http://www.microsoft.com/surface/support/hardware-and-drivers/sound-volume-and-speakers) + on Surface.com.\",\n \"confidenceScore\": 43.97,\n \"id\": 68,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {},\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: 375616dd-f630-4153-9fae-7f9790285734 + content-length: '7781' + content-type: application/json; charset=utf-8 + date: Fri, 25 Jun 2021 19:41:17 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '343' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_dictparams.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_dictparams.yaml new file mode 100644 index 000000000000..0f45d6180d45 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_dictparams.yaml @@ -0,0 +1,54 @@ +interactions: +- request: + body: '{"question": "How long should my Surface battery last?", "top": 3, "userId": + "sd53lsY=", "confidenceScoreThreshold": 0.2, "answerSpanRequest": {"enable": + true, "confidenceScoreThreshold": 0.2, "topAnswersWithSpan": 1}, "includeUnstructuredSources": + true}' + headers: + Accept: + - application/json + Content-Length: + - '254' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Make + your battery last\"\n ],\n \"answer\": \"**Make your battery last**\\n\\nFor + info on how to care for your battery and power supply, conserve power, and + make your Surface battery last longer, see [Surface battery and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\",\n \"confidenceScore\": 0.9292,\n \"id\": 27,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"make your battery last\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n },\n {\n \"questions\": [\n \"Check the battery + level\"\n ],\n \"answer\": \"**Check the battery level**\\n\\nYou + can check the battery level from the lock screen or the desktop:\",\n \"confidenceScore\": + 0.3583,\n \"id\": 24,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"check the battery + level\"\n },\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": []\n }\n },\n {\n \"questions\": [\n + \ \"Desktop taskbar.\"\n ],\n \"answer\": \"**Desktop taskbar.**\\n\\nBattery + status appears at the right side of the taskbar. Select the battery icon for + info about the charging and battery status, including the percent remaining. + \u272A\",\n \"confidenceScore\": 0.2229,\n \"id\": 26,\n \"source\": + \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": {},\n \"dialog\": + {\n \"isContextOnly\": false,\n \"prompts\": []\n }\n }\n + \ ]\n}" + headers: + apim-request-id: d3136678-d454-41f9-b064-ebf1b207e82b + content-length: '1609' + content-type: application/json; charset=utf-8 + date: Wed, 30 Jun 2021 15:36:56 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '949' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_followup.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_followup.yaml new file mode 100644 index 000000000000..f52047a64514 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_knowledgebase_async.test_query_knowledgebase_with_followup.yaml @@ -0,0 +1,115 @@ +interactions: +- request: + body: '{"question": "How long should my Surface battery last?", "top": 3, "userId": + "sd53lsY=", "confidenceScoreThreshold": 0.2, "answerSpanRequest": {"enable": + true, "confidenceScoreThreshold": 0.2, "topAnswersWithSpan": 1}, "includeUnstructuredSources": + true}' + headers: + Accept: + - application/json + Content-Length: + - '254' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Make + your battery last\"\n ],\n \"answer\": \"**Make your battery last**\\n\\nFor + info on how to care for your battery and power supply, conserve power, and + make your Surface battery last longer, see [Surface battery and power](http://www.microsoft.com/surface/support/hardware-and-drivers/battery-and-power) + on Surface.com.\",\n \"confidenceScore\": 0.9292,\n \"id\": 27,\n + \ \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"make your battery last\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n },\n {\n \"questions\": [\n \"Check the battery + level\"\n ],\n \"answer\": \"**Check the battery level**\\n\\nYou + can check the battery level from the lock screen or the desktop:\",\n \"confidenceScore\": + 0.3583,\n \"id\": 24,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"check the battery + level\"\n },\n \"dialog\": {\n \"isContextOnly\": false,\n + \ \"prompts\": []\n }\n },\n {\n \"questions\": [\n + \ \"Desktop taskbar.\"\n ],\n \"answer\": \"**Desktop taskbar.**\\n\\nBattery + status appears at the right side of the taskbar. Select the battery icon for + info about the charging and battery status, including the percent remaining. + \u272A\",\n \"confidenceScore\": 0.2229,\n \"id\": 26,\n \"source\": + \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": {},\n \"dialog\": + {\n \"isContextOnly\": false,\n \"prompts\": []\n }\n }\n + \ ]\n}" + headers: + apim-request-id: 7cd6d31a-771e-4cdb-a6be-7a1504295914 + content-length: '1609' + content-type: application/json; charset=utf-8 + date: Wed, 30 Jun 2021 15:14:34 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '970' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +- request: + body: '{"question": "How long it takes to charge Surface?", "top": 3, "userId": + "sd53lsY=", "confidenceScoreThreshold": 0.2, "context": {"previousQnaId": 27, + "previousUserQuery": "How long should my Surface battery last?"}, "answerSpanRequest": + {"enable": true, "confidenceScoreThreshold": 0.2, "topAnswersWithSpan": 1}, + "includeUnstructuredSources": true}' + headers: + Accept: + - application/json + Content-Length: + - '349' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=test-project&deploymentName=test&api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"questions\": [\n \"Power + and charging\"\n ],\n \"answer\": \"**Power and charging**\\n\\nIt + takes two to four hours to charge the Surface Pro 4 battery fully from an + empty state. It can take longer if you\u2019re using your Surface for power-intensive + activities like gaming or video streaming while you\u2019re charging it.\\n\\nYou + can use the USB port on your Surface Pro 4 power supply to charge other devices, + like a phone, while your Surface charges. The USB port on the power supply + is only for charging, not for data transfer. If you want to use a USB device, + plug it into the USB port on your Surface.\",\n \"confidenceScore\": + 0.6545000000000001,\n \"id\": 23,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n + \ \"metadata\": {\n \"explicitlytaggedheading\": \"power and charging\"\n + \ },\n \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + [\n {\n \"displayOrder\": 0,\n \"qnaId\": 24,\n + \ \"displayText\": \"Check the battery level\"\n },\n {\n + \ \"displayOrder\": 1,\n \"qnaId\": 25,\n \"displayText\": + \"Lock screen.\"\n },\n {\n \"displayOrder\": + 2,\n \"qnaId\": 26,\n \"displayText\": \"Desktop taskbar.\"\n + \ },\n {\n \"displayOrder\": 3,\n \"qnaId\": + 27,\n \"displayText\": \"Make your battery last\"\n }\n + \ ]\n },\n \"answerSpan\": {\n \"text\": \"two to four + hours\",\n \"confidenceScore\": 30.86,\n \"offset\": 33,\n \"length\": + 18\n }\n },\n {\n \"questions\": [\n \"Charge your + Surface Pro 4\"\n ],\n \"answer\": \"**Charge your Surface Pro 4**\\n\\n1. + \ Connect the two parts of the power cord.\\n\\n2. Connect the power cord + securely to the charging port.\\n\\n3. Plug the power supply into an electrical + outlet.\",\n \"confidenceScore\": 0.31989999999999996,\n \"id\": + 19,\n \"source\": \"surface-pro-4-user-guide-EN.pdf\",\n \"metadata\": + {\n \"explicitlytaggedheading\": \"charge your surface pro 4\"\n },\n + \ \"dialog\": {\n \"isContextOnly\": false,\n \"prompts\": + []\n }\n }\n ]\n}" + headers: + apim-request-id: db4190a2-426a-4932-8d83-dd14b10f4b37 + content-length: '2177' + content-type: application/json; charset=utf-8 + date: Wed, 30 Jun 2021 15:14:35 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '1060' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-knowledgebases?projectName=190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c&deploymentName=test&api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text.yaml new file mode 100644 index 000000000000..0b344818fda5 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text.yaml @@ -0,0 +1,161 @@ +interactions: +- request: + body: '{"question": "What is the meaning of life?", "records": [{"id": "doc1", + "text": "abc Graphics Surprise, surprise -- our 4K "}, {"id": "doc2", "text": + "e graphics card. While the Nvidia GeForce MX250 GPU isn''t meant for demanding + gaming, it is a step up from integrated graphics as proven by comparing it to + the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 + on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading + to the discrete graphics gives the Envy 13 better performance than the Notebook + 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium + laptop average (86,937). While the Nvidia GeForce MX250 GPU isn''t meant for + demanding gaming, it is a step up from integrated graphics as proven by comparing + it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at + 92 frames per second on "}, {"id": "doc3", "text": "Graphics Surprise, surprise + -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce + MX250 GPU isn''t meant for demanding gaming, it is a step up from integrated + graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The + MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark + while the base model scored a 82,270. Upgrading to the discrete graphics gives + the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface + Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While + the Nvidia GeForce MX250 GPU isn''t meant for demanding gaming, it is a step + up from integrated graphics as proven by comparing it to the UHD 620 GPU in + the FHD model. We played the racing game Dirt 3 at 92 frames per second on + the MX250 model, which is well above our 30-fps playability, the category average + (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA + (45 fps) fell flat on this real-world test but ran better than the base model + Envy 13 (31 fps). Audio I had a good ol'' time groovin'' to the sound of the + Envy 13''s crisp speakers. HP went all out with the Envy, placing dual speakers + on the underside of the chassis along with a third, top-firing driver above + the keyboard. Devon Gilfillian''s funky jam \"Here and Now\" boomed smooth, + soulful tunes throughout my small apartment. The twang of the electric guitar + played nicely with the thudding percussion but never overshadowed Gilfillian + or the female backup vocals. Bang & Olufsen software comes preinstalled on + the Envy 13, with equalizer controls so you can adjust the bass, midrange and + treble to your liking. But even out of the box, you''ll enjoy great sound without + having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p + non-touch display if battery life is important to you. The FHD model endured + for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 + minutes on our battery test, which involves continuous web browsing over Wi-Fi + at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest + Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), + Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but + powered down long before the 1080p version. Webcam The 720p webcam on the + Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room + was covered in a haze of visual noise. My beard and hair were unkempt blobs, + while my eyes looked like they were drawn on by a pointillist painter. If there''s + one positive, it''s that the lens captures natural colors and even extracted + the different shades of gray in my T-shirt. On the right edge of the Envy + 13 is a physical kill switch that cuts the power to the webcam so you can feel + reassured that nobody is snooping on you. Heat Leave the lapdesk at home + - you don''t have to worry about the Envy 13 overheating. After I played + a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with + a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) + and underside (90 degrees) also remained well below our 95-degree comfort threshold. + Even the toastiest part of the machine, the lower-left edge on the underside, + topped out at 94 degrees. Software and Warranty It''s a shame that a laptop + with such beautiful hardware ships with such ugly software. Pre-installed on + this machine are entirely too many programs that could either be packaged together + or omitted altogether. HP provides an app called Audio Switch, which simply + lets you switch your audio input/output between the internal speakers and headphones. + As the same implies, HP''s Command Center is where you can get information about + your Envy 13 but also switch the thermal profiles between comfort and performance. + Along with support documentation, HP also bundles in a setup program called + JumpStart, a program for connecting printers and a redundant system-info app + called Event Utility. Also installed on the Envy 13''s Windows 10 Home OS + are several Microsoft apps, including Simple Solitaire, Candy Crush Friends + and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee + Security. HP ships the Envy 13 with a one-year warranty. See how HP did on + our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The + Envy 13 has cemented its standing as the ultimate laptop for college students + or travelers. Along with 11-plus hours of battery life (on the FHD model), the + Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. + Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less + than the competition. In many ways, the Envy 13 is what we wanted the new MacBook + Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air + would be: fast, attractive and affordable. Just be sure to buy the right model. + We strongly recommend the 1080p version over the 4K model because it lasts several + hours longer on a charge and costs less. In fact, if we were reviewing the 4K + model separately, we''d only give it a 3.5 rating. You should also consider + the Envy 13 with a 10th Gen CPU, although we haven''t gotten the chance to review + it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of + many good options. We also recommend the Samsung Notebook 9 Pro, which has a + similarly premium design but much better battery life than the 4K Envy. The + Microsoft Surface Laptop 2 is another recommended alternative, though you might + want to wait a few months for the rumored Surface Laptop 3. Overall, the HP + Envy 13 is a fantastic laptop that checks all the right boxes --- as long as + you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth + 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html + Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard + Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 + x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, + USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB + Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB + Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel + Wireless-AC 9560 "}], "language": "en", "stringIndexType": "TextElements_v8"}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '7447' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"answer\": \"Battery Life Get an + Envy 13 with the 1080p non-touch display if battery life is important to you. + \ The FHD model endured for 11 hours and 11 minutes whereas the 4K model + lasted only 4 hours and 36 minutes on our battery test, which involves continuous + web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best + Battery Life - Longest Lasting Laptop Batteries Competing laptops like the + ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) + outstayed the 4K Envy 13 but powered down long before the 1080p version.\",\n + \ \"confidenceScore\": 0.01745828054845333,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"Battery Life\",\n \"confidenceScore\": + 0.26247412,\n \"offset\": 0,\n \"length\": 12\n },\n \"offset\": + 1779,\n \"length\": 555\n },\n {\n \"answer\": \"Along with + 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, + ultraportable chassis, fast performance, and powerful speakers. Best of all, + the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. + In many ways, the Envy 13 is what we wanted the new MacBook Air to be.\",\n + \ \"confidenceScore\": 0.00940172653645277,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.35305238,\n \"offset\": 27,\n \"length\": 13\n },\n \"offset\": + 4508,\n \"length\": 319\n },\n {\n \"answer\": \"We also recommend + the Samsung Notebook 9 Pro, which has a similarly premium design but much + better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another + recommended alternative, though you might want to wait a few months for the + rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop + that checks all the right boxes --- as long as you buy the 1080p model.\",\n + \ \"confidenceScore\": 0.0070572528056800365,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.59143245,\n \"offset\": 98,\n \"length\": 13\n },\n \"offset\": + 5391,\n \"length\": 393\n }\n ]\n}" + headers: + apim-request-id: + - b7473b1a-9903-42a4-897f-d095ddfc68f8 + content-length: + - '2147' + content-type: + - application/json; charset=utf-8 + date: + - Fri, 25 Jun 2021 19:41:18 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '322' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text_llc.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text_llc.yaml new file mode 100644 index 000000000000..7d7c2b48a8e8 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text_llc.yaml @@ -0,0 +1,161 @@ +interactions: +- request: + body: '{"question": "What is the meaning of life?", "records": [{"text": "abc + Graphics Surprise, surprise -- our 4K ", "id": "doc1"}, {"text": "e graphics + card. While the Nvidia GeForce MX250 GPU isn''t meant for demanding gaming, + it is a step up from integrated graphics as proven by comparing it to the UHD + 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the + Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading + to the discrete graphics gives the Envy 13 better performance than the Notebook + 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium + laptop average (86,937). While the Nvidia GeForce MX250 GPU isn''t meant for + demanding gaming, it is a step up from integrated graphics as proven by comparing + it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at + 92 frames per second on ", "id": "doc2"}, {"text": "Graphics Surprise, surprise + -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce + MX250 GPU isn''t meant for demanding gaming, it is a step up from integrated + graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The + MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark + while the base model scored a 82,270. Upgrading to the discrete graphics gives + the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface + Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While + the Nvidia GeForce MX250 GPU isn''t meant for demanding gaming, it is a step + up from integrated graphics as proven by comparing it to the UHD 620 GPU in + the FHD model. We played the racing game Dirt 3 at 92 frames per second on + the MX250 model, which is well above our 30-fps playability, the category average + (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA + (45 fps) fell flat on this real-world test but ran better than the base model + Envy 13 (31 fps). Audio I had a good ol'' time groovin'' to the sound of the + Envy 13''s crisp speakers. HP went all out with the Envy, placing dual speakers + on the underside of the chassis along with a third, top-firing driver above + the keyboard. Devon Gilfillian''s funky jam \"Here and Now\" boomed smooth, + soulful tunes throughout my small apartment. The twang of the electric guitar + played nicely with the thudding percussion but never overshadowed Gilfillian + or the female backup vocals. Bang & Olufsen software comes preinstalled on + the Envy 13, with equalizer controls so you can adjust the bass, midrange and + treble to your liking. But even out of the box, you''ll enjoy great sound without + having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p + non-touch display if battery life is important to you. The FHD model endured + for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 + minutes on our battery test, which involves continuous web browsing over Wi-Fi + at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest + Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), + Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but + powered down long before the 1080p version. Webcam The 720p webcam on the + Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room + was covered in a haze of visual noise. My beard and hair were unkempt blobs, + while my eyes looked like they were drawn on by a pointillist painter. If there''s + one positive, it''s that the lens captures natural colors and even extracted + the different shades of gray in my T-shirt. On the right edge of the Envy + 13 is a physical kill switch that cuts the power to the webcam so you can feel + reassured that nobody is snooping on you. Heat Leave the lapdesk at home + - you don''t have to worry about the Envy 13 overheating. After I played + a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with + a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) + and underside (90 degrees) also remained well below our 95-degree comfort threshold. + Even the toastiest part of the machine, the lower-left edge on the underside, + topped out at 94 degrees. Software and Warranty It''s a shame that a laptop + with such beautiful hardware ships with such ugly software. Pre-installed on + this machine are entirely too many programs that could either be packaged together + or omitted altogether. HP provides an app called Audio Switch, which simply + lets you switch your audio input/output between the internal speakers and headphones. + As the same implies, HP''s Command Center is where you can get information about + your Envy 13 but also switch the thermal profiles between comfort and performance. + Along with support documentation, HP also bundles in a setup program called + JumpStart, a program for connecting printers and a redundant system-info app + called Event Utility. Also installed on the Envy 13''s Windows 10 Home OS + are several Microsoft apps, including Simple Solitaire, Candy Crush Friends + and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee + Security. HP ships the Envy 13 with a one-year warranty. See how HP did on + our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The + Envy 13 has cemented its standing as the ultimate laptop for college students + or travelers. Along with 11-plus hours of battery life (on the FHD model), the + Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. + Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less + than the competition. In many ways, the Envy 13 is what we wanted the new MacBook + Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air + would be: fast, attractive and affordable. Just be sure to buy the right model. + We strongly recommend the 1080p version over the 4K model because it lasts several + hours longer on a charge and costs less. In fact, if we were reviewing the 4K + model separately, we''d only give it a 3.5 rating. You should also consider + the Envy 13 with a 10th Gen CPU, although we haven''t gotten the chance to review + it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of + many good options. We also recommend the Samsung Notebook 9 Pro, which has a + similarly premium design but much better battery life than the 4K Envy. The + Microsoft Surface Laptop 2 is another recommended alternative, though you might + want to wait a few months for the rumored Surface Laptop 3. Overall, the HP + Envy 13 is a fantastic laptop that checks all the right boxes --- as long as + you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth + 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html + Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard + Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 + x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, + USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB + Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB + Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel + Wireless-AC 9560 ", "id": "doc3"}], "language": "en"}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '7409' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"answer\": \"Battery Life Get an + Envy 13 with the 1080p non-touch display if battery life is important to you. + \ The FHD model endured for 11 hours and 11 minutes whereas the 4K model + lasted only 4 hours and 36 minutes on our battery test, which involves continuous + web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best + Battery Life - Longest Lasting Laptop Batteries Competing laptops like the + ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) + outstayed the 4K Envy 13 but powered down long before the 1080p version.\",\n + \ \"confidenceScore\": 0.017458289861679077,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"Battery Life\",\n \"confidenceScore\": + 0.26247412,\n \"offset\": 0,\n \"length\": 12\n },\n \"offset\": + 1779,\n \"length\": 555\n },\n {\n \"answer\": \"Along with + 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, + ultraportable chassis, fast performance, and powerful speakers. Best of all, + the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. + In many ways, the Envy 13 is what we wanted the new MacBook Air to be.\",\n + \ \"confidenceScore\": 0.00940172653645277,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.35305238,\n \"offset\": 27,\n \"length\": 13\n },\n \"offset\": + 4508,\n \"length\": 319\n },\n {\n \"answer\": \"We also recommend + the Samsung Notebook 9 Pro, which has a similarly premium design but much + better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another + recommended alternative, though you might want to wait a few months for the + rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop + that checks all the right boxes --- as long as you buy the 1080p model.\",\n + \ \"confidenceScore\": 0.007057250943034887,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.59143245,\n \"offset\": 98,\n \"length\": 13\n },\n \"offset\": + 5391,\n \"length\": 393\n }\n ]\n}" + headers: + apim-request-id: + - eae82c61-0d7f-4130-8c21-680060b8a75d + content-length: + - '2147' + content-type: + - application/json; charset=utf-8 + date: + - Fri, 25 Jun 2021 19:41:19 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '287' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text_with_dictparams.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text_with_dictparams.yaml new file mode 100644 index 000000000000..6d243459afcd --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text.test_query_text_with_dictparams.yaml @@ -0,0 +1,67 @@ +interactions: +- request: + body: '{"question": "How long it takes to charge surface?", "records": [{"text": + "Power and charging. It takes two to four hours to charge the Surface Pro 4 + battery fully from an empty state. It can take longer if you\u2019re using your + Surface for power-intensive activities like gaming or video streaming while + you\u2019re charging it.", "id": "1"}, {"text": "You can use the USB port on + your Surface Pro 4 power supply to charge other devices, like a phone, while + your Surface charges. The USB port on the power supply is only for charging, + not for data transfer. If you want to use a USB device, plug it into the USB + port on your Surface.", "id": "2"}], "language": "en"}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + Connection: + - keep-alive + Content-Length: + - '668' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"answer\": \"Power and charging. + It takes two to four hours to charge the Surface Pro 4 battery fully from + an empty state. It can take longer if you\u2019re using your Surface for power-intensive + activities like gaming or video streaming while you\u2019re charging it.\",\n + \ \"confidenceScore\": 0.9298818707466125,\n \"id\": \"1\",\n \"answerSpan\": + {\n \"text\": \"two to four hours\",\n \"confidenceScore\": + 0.98579097,\n \"offset\": 28,\n \"length\": 18\n },\n \"offset\": + 0,\n \"length\": 245\n },\n {\n \"answer\": \"It takes two + to four hours to charge the Surface Pro 4 battery fully from an empty state. + It can take longer if you\u2019re using your Surface for power-intensive activities + like gaming or video streaming while you\u2019re charging it.\",\n \"confidenceScore\": + 0.9254359602928162,\n \"id\": \"1\",\n \"answerSpan\": {\n \"text\": + \"two to four hours\",\n \"confidenceScore\": 0.98562825,\n \"offset\": + 8,\n \"length\": 18\n },\n \"offset\": 20,\n \"length\": + 225\n },\n {\n \"answer\": \"It can take longer if you\u2019re + using your Surface for power-intensive activities like gaming or video streaming + while you\u2019re charging it.\",\n \"confidenceScore\": 0.05503518134355545,\n + \ \"id\": \"1\",\n \"answerSpan\": {\n \"text\": \"longer\",\n + \ \"confidenceScore\": 0.624118,\n \"offset\": 11,\n \"length\": + 7\n },\n \"offset\": 110,\n \"length\": 135\n }\n ]\n}" + headers: + apim-request-id: + - f38bdca7-e368-46b0-a09a-c469b36540bf + content-length: + - '1479' + content-type: + - application/json; charset=utf-8 + date: + - Wed, 30 Jun 2021 15:07:14 GMT + strict-transport-security: + - max-age=31536000; includeSubDomains; preload + x-content-type-options: + - nosniff + x-envoy-upstream-service-time: + - '315' + status: + code: 200 + message: OK +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text.yaml new file mode 100644 index 000000000000..7beb994811cf --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text.yaml @@ -0,0 +1,151 @@ +interactions: +- request: + body: '{"question": "What is the meaning of life?", "records": [{"id": "doc1", + "text": "abc Graphics Surprise, surprise -- our 4K "}, {"id": "doc2", "text": + "e graphics card. While the Nvidia GeForce MX250 GPU isn''t meant for demanding + gaming, it is a step up from integrated graphics as proven by comparing it to + the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 + on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading + to the discrete graphics gives the Envy 13 better performance than the Notebook + 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium + laptop average (86,937). While the Nvidia GeForce MX250 GPU isn''t meant for + demanding gaming, it is a step up from integrated graphics as proven by comparing + it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at + 92 frames per second on "}, {"id": "doc3", "text": "Graphics Surprise, surprise + -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce + MX250 GPU isn''t meant for demanding gaming, it is a step up from integrated + graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The + MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark + while the base model scored a 82,270. Upgrading to the discrete graphics gives + the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface + Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While + the Nvidia GeForce MX250 GPU isn''t meant for demanding gaming, it is a step + up from integrated graphics as proven by comparing it to the UHD 620 GPU in + the FHD model. We played the racing game Dirt 3 at 92 frames per second on + the MX250 model, which is well above our 30-fps playability, the category average + (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA + (45 fps) fell flat on this real-world test but ran better than the base model + Envy 13 (31 fps). Audio I had a good ol'' time groovin'' to the sound of the + Envy 13''s crisp speakers. HP went all out with the Envy, placing dual speakers + on the underside of the chassis along with a third, top-firing driver above + the keyboard. Devon Gilfillian''s funky jam \"Here and Now\" boomed smooth, + soulful tunes throughout my small apartment. The twang of the electric guitar + played nicely with the thudding percussion but never overshadowed Gilfillian + or the female backup vocals. Bang & Olufsen software comes preinstalled on + the Envy 13, with equalizer controls so you can adjust the bass, midrange and + treble to your liking. But even out of the box, you''ll enjoy great sound without + having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p + non-touch display if battery life is important to you. The FHD model endured + for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 + minutes on our battery test, which involves continuous web browsing over Wi-Fi + at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest + Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), + Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but + powered down long before the 1080p version. Webcam The 720p webcam on the + Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room + was covered in a haze of visual noise. My beard and hair were unkempt blobs, + while my eyes looked like they were drawn on by a pointillist painter. If there''s + one positive, it''s that the lens captures natural colors and even extracted + the different shades of gray in my T-shirt. On the right edge of the Envy + 13 is a physical kill switch that cuts the power to the webcam so you can feel + reassured that nobody is snooping on you. Heat Leave the lapdesk at home + - you don''t have to worry about the Envy 13 overheating. After I played + a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with + a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) + and underside (90 degrees) also remained well below our 95-degree comfort threshold. + Even the toastiest part of the machine, the lower-left edge on the underside, + topped out at 94 degrees. Software and Warranty It''s a shame that a laptop + with such beautiful hardware ships with such ugly software. Pre-installed on + this machine are entirely too many programs that could either be packaged together + or omitted altogether. HP provides an app called Audio Switch, which simply + lets you switch your audio input/output between the internal speakers and headphones. + As the same implies, HP''s Command Center is where you can get information about + your Envy 13 but also switch the thermal profiles between comfort and performance. + Along with support documentation, HP also bundles in a setup program called + JumpStart, a program for connecting printers and a redundant system-info app + called Event Utility. Also installed on the Envy 13''s Windows 10 Home OS + are several Microsoft apps, including Simple Solitaire, Candy Crush Friends + and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee + Security. HP ships the Envy 13 with a one-year warranty. See how HP did on + our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The + Envy 13 has cemented its standing as the ultimate laptop for college students + or travelers. Along with 11-plus hours of battery life (on the FHD model), the + Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. + Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less + than the competition. In many ways, the Envy 13 is what we wanted the new MacBook + Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air + would be: fast, attractive and affordable. Just be sure to buy the right model. + We strongly recommend the 1080p version over the 4K model because it lasts several + hours longer on a charge and costs less. In fact, if we were reviewing the 4K + model separately, we''d only give it a 3.5 rating. You should also consider + the Envy 13 with a 10th Gen CPU, although we haven''t gotten the chance to review + it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of + many good options. We also recommend the Samsung Notebook 9 Pro, which has a + similarly premium design but much better battery life than the 4K Envy. The + Microsoft Surface Laptop 2 is another recommended alternative, though you might + want to wait a few months for the rumored Surface Laptop 3. Overall, the HP + Envy 13 is a fantastic laptop that checks all the right boxes --- as long as + you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth + 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html + Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard + Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 + x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, + USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB + Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB + Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel + Wireless-AC 9560 "}], "language": "en", "stringIndexType": "TextElements_v8"}' + headers: + Accept: + - application/json + Content-Length: + - '7447' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"answer\": \"Battery Life Get an + Envy 13 with the 1080p non-touch display if battery life is important to you. + \ The FHD model endured for 11 hours and 11 minutes whereas the 4K model + lasted only 4 hours and 36 minutes on our battery test, which involves continuous + web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best + Battery Life - Longest Lasting Laptop Batteries Competing laptops like the + ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) + outstayed the 4K Envy 13 but powered down long before the 1080p version.\",\n + \ \"confidenceScore\": 0.017458289861679077,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"Battery Life\",\n \"confidenceScore\": + 0.26247412,\n \"offset\": 0,\n \"length\": 12\n },\n \"offset\": + 1779,\n \"length\": 555\n },\n {\n \"answer\": \"Along with + 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, + ultraportable chassis, fast performance, and powerful speakers. Best of all, + the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. + In many ways, the Envy 13 is what we wanted the new MacBook Air to be.\",\n + \ \"confidenceScore\": 0.00940172653645277,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.35305238,\n \"offset\": 27,\n \"length\": 13\n },\n \"offset\": + 4508,\n \"length\": 319\n },\n {\n \"answer\": \"We also recommend + the Samsung Notebook 9 Pro, which has a similarly premium design but much + better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another + recommended alternative, though you might want to wait a few months for the + rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop + that checks all the right boxes --- as long as you buy the 1080p model.\",\n + \ \"confidenceScore\": 0.0070572528056800365,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.5914322,\n \"offset\": 98,\n \"length\": 13\n },\n \"offset\": + 5391,\n \"length\": 393\n }\n ]\n}" + headers: + apim-request-id: f7d22644-9f95-4e63-a16c-e111f73bc24d + content-length: '2147' + content-type: application/json; charset=utf-8 + date: Fri, 25 Jun 2021 19:41:19 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '284' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text_llc.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text_llc.yaml new file mode 100644 index 000000000000..8f3d6b71ab91 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text_llc.yaml @@ -0,0 +1,151 @@ +interactions: +- request: + body: '{"question": "What is the meaning of life?", "records": [{"text": "abc + Graphics Surprise, surprise -- our 4K ", "id": "doc1"}, {"text": "e graphics + card. While the Nvidia GeForce MX250 GPU isn''t meant for demanding gaming, + it is a step up from integrated graphics as proven by comparing it to the UHD + 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the + Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading + to the discrete graphics gives the Envy 13 better performance than the Notebook + 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium + laptop average (86,937). While the Nvidia GeForce MX250 GPU isn''t meant for + demanding gaming, it is a step up from integrated graphics as proven by comparing + it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at + 92 frames per second on ", "id": "doc2"}, {"text": "Graphics Surprise, surprise + -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce + MX250 GPU isn''t meant for demanding gaming, it is a step up from integrated + graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The + MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark + while the base model scored a 82,270. Upgrading to the discrete graphics gives + the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface + Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While + the Nvidia GeForce MX250 GPU isn''t meant for demanding gaming, it is a step + up from integrated graphics as proven by comparing it to the UHD 620 GPU in + the FHD model. We played the racing game Dirt 3 at 92 frames per second on + the MX250 model, which is well above our 30-fps playability, the category average + (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA + (45 fps) fell flat on this real-world test but ran better than the base model + Envy 13 (31 fps). Audio I had a good ol'' time groovin'' to the sound of the + Envy 13''s crisp speakers. HP went all out with the Envy, placing dual speakers + on the underside of the chassis along with a third, top-firing driver above + the keyboard. Devon Gilfillian''s funky jam \"Here and Now\" boomed smooth, + soulful tunes throughout my small apartment. The twang of the electric guitar + played nicely with the thudding percussion but never overshadowed Gilfillian + or the female backup vocals. Bang & Olufsen software comes preinstalled on + the Envy 13, with equalizer controls so you can adjust the bass, midrange and + treble to your liking. But even out of the box, you''ll enjoy great sound without + having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p + non-touch display if battery life is important to you. The FHD model endured + for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 + minutes on our battery test, which involves continuous web browsing over Wi-Fi + at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest + Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), + Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but + powered down long before the 1080p version. Webcam The 720p webcam on the + Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room + was covered in a haze of visual noise. My beard and hair were unkempt blobs, + while my eyes looked like they were drawn on by a pointillist painter. If there''s + one positive, it''s that the lens captures natural colors and even extracted + the different shades of gray in my T-shirt. On the right edge of the Envy + 13 is a physical kill switch that cuts the power to the webcam so you can feel + reassured that nobody is snooping on you. Heat Leave the lapdesk at home + - you don''t have to worry about the Envy 13 overheating. After I played + a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with + a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) + and underside (90 degrees) also remained well below our 95-degree comfort threshold. + Even the toastiest part of the machine, the lower-left edge on the underside, + topped out at 94 degrees. Software and Warranty It''s a shame that a laptop + with such beautiful hardware ships with such ugly software. Pre-installed on + this machine are entirely too many programs that could either be packaged together + or omitted altogether. HP provides an app called Audio Switch, which simply + lets you switch your audio input/output between the internal speakers and headphones. + As the same implies, HP''s Command Center is where you can get information about + your Envy 13 but also switch the thermal profiles between comfort and performance. + Along with support documentation, HP also bundles in a setup program called + JumpStart, a program for connecting printers and a redundant system-info app + called Event Utility. Also installed on the Envy 13''s Windows 10 Home OS + are several Microsoft apps, including Simple Solitaire, Candy Crush Friends + and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee + Security. HP ships the Envy 13 with a one-year warranty. See how HP did on + our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The + Envy 13 has cemented its standing as the ultimate laptop for college students + or travelers. Along with 11-plus hours of battery life (on the FHD model), the + Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. + Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less + than the competition. In many ways, the Envy 13 is what we wanted the new MacBook + Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air + would be: fast, attractive and affordable. Just be sure to buy the right model. + We strongly recommend the 1080p version over the 4K model because it lasts several + hours longer on a charge and costs less. In fact, if we were reviewing the 4K + model separately, we''d only give it a 3.5 rating. You should also consider + the Envy 13 with a 10th Gen CPU, although we haven''t gotten the chance to review + it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of + many good options. We also recommend the Samsung Notebook 9 Pro, which has a + similarly premium design but much better battery life than the 4K Envy. The + Microsoft Surface Laptop 2 is another recommended alternative, though you might + want to wait a few months for the rumored Surface Laptop 3. Overall, the HP + Envy 13 is a fantastic laptop that checks all the right boxes --- as long as + you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth + 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html + Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard + Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 + x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, + USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB + Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB + Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel + Wireless-AC 9560 ", "id": "doc3"}], "language": "en"}' + headers: + Accept: + - application/json + Content-Length: + - '7409' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"answer\": \"Battery Life Get an + Envy 13 with the 1080p non-touch display if battery life is important to you. + \ The FHD model endured for 11 hours and 11 minutes whereas the 4K model + lasted only 4 hours and 36 minutes on our battery test, which involves continuous + web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best + Battery Life - Longest Lasting Laptop Batteries Competing laptops like the + ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) + outstayed the 4K Envy 13 but powered down long before the 1080p version.\",\n + \ \"confidenceScore\": 0.01745828054845333,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"Battery Life\",\n \"confidenceScore\": + 0.26247412,\n \"offset\": 0,\n \"length\": 12\n },\n \"offset\": + 1779,\n \"length\": 555\n },\n {\n \"answer\": \"Along with + 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, + ultraportable chassis, fast performance, and powerful speakers. Best of all, + the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. + In many ways, the Envy 13 is what we wanted the new MacBook Air to be.\",\n + \ \"confidenceScore\": 0.00940172653645277,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.35305238,\n \"offset\": 27,\n \"length\": 13\n },\n \"offset\": + 4508,\n \"length\": 319\n },\n {\n \"answer\": \"We also recommend + the Samsung Notebook 9 Pro, which has a similarly premium design but much + better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another + recommended alternative, though you might want to wait a few months for the + rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop + that checks all the right boxes --- as long as you buy the 1080p model.\",\n + \ \"confidenceScore\": 0.0070572528056800365,\n \"id\": \"doc3\",\n + \ \"answerSpan\": {\n \"text\": \"battery life\",\n \"confidenceScore\": + 0.59143245,\n \"offset\": 98,\n \"length\": 13\n },\n \"offset\": + 5391,\n \"length\": 393\n }\n ]\n}" + headers: + apim-request-id: ba49fbf2-8c63-4ae1-b5d6-2b2ec86d8776 + content-length: '2147' + content-type: application/json; charset=utf-8 + date: Fri, 25 Jun 2021 19:41:20 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '272' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text_with_dictparams.yaml b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text_with_dictparams.yaml new file mode 100644 index 000000000000..56e6e56f50d3 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/recordings/test_query_text_async.test_query_text_with_dictparams.yaml @@ -0,0 +1,57 @@ +interactions: +- request: + body: '{"question": "How long it takes to charge surface?", "records": [{"text": + "Power and charging. It takes two to four hours to charge the Surface Pro 4 + battery fully from an empty state. It can take longer if you\u2019re using your + Surface for power-intensive activities like gaming or video streaming while + you\u2019re charging it.", "id": "1"}, {"text": "You can use the USB port on + your Surface Pro 4 power supply to charge other devices, like a phone, while + your Surface charges. The USB port on the power supply is only for charging, + not for data transfer. If you want to use a USB device, plug it into the USB + port on your Surface.", "id": "2"}], "language": "en"}' + headers: + Accept: + - application/json + Content-Length: + - '668' + Content-Type: + - application/json + User-Agent: + - azsdk-python-ai-language-questionanswering/1.0.0b1 Python/3.7.4 (Windows-10-10.0.19041-SP0) + method: POST + uri: https://test-resource.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview + response: + body: + string: "{\n \"answers\": [\n {\n \"answer\": \"Power and charging. + It takes two to four hours to charge the Surface Pro 4 battery fully from + an empty state. It can take longer if you\u2019re using your Surface for power-intensive + activities like gaming or video streaming while you\u2019re charging it.\",\n + \ \"confidenceScore\": 0.9298818111419678,\n \"id\": \"1\",\n \"answerSpan\": + {\n \"text\": \"two to four hours\",\n \"confidenceScore\": + 0.98579097,\n \"offset\": 28,\n \"length\": 18\n },\n \"offset\": + 0,\n \"length\": 245\n },\n {\n \"answer\": \"It takes two + to four hours to charge the Surface Pro 4 battery fully from an empty state. + It can take longer if you\u2019re using your Surface for power-intensive activities + like gaming or video streaming while you\u2019re charging it.\",\n \"confidenceScore\": + 0.9254359602928162,\n \"id\": \"1\",\n \"answerSpan\": {\n \"text\": + \"two to four hours\",\n \"confidenceScore\": 0.9856282,\n \"offset\": + 8,\n \"length\": 18\n },\n \"offset\": 20,\n \"length\": + 225\n },\n {\n \"answer\": \"It can take longer if you\u2019re + using your Surface for power-intensive activities like gaming or video streaming + while you\u2019re charging it.\",\n \"confidenceScore\": 0.05503518134355545,\n + \ \"id\": \"1\",\n \"answerSpan\": {\n \"text\": \"longer\",\n + \ \"confidenceScore\": 0.624118,\n \"offset\": 11,\n \"length\": + 7\n },\n \"offset\": 110,\n \"length\": 135\n }\n ]\n}" + headers: + apim-request-id: fc0cf99e-2f1a-4cf1-8234-4d40c42eaca7 + content-length: '1478' + content-type: application/json; charset=utf-8 + date: Wed, 30 Jun 2021 15:07:15 GMT + strict-transport-security: max-age=31536000; includeSubDomains; preload + x-content-type-options: nosniff + x-envoy-upstream-service-time: '362' + status: + code: 200 + message: OK + url: https://wuppe.api.cognitive.microsoft.com/language/:query-text?api-version=2021-05-01-preview +version: 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase.py new file mode 100644 index 000000000000..470669ffa070 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase.py @@ -0,0 +1,314 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os + +from azure.core.exceptions import HttpResponseError, ClientAuthenticationError +from azure.core.credentials import AzureKeyCredential + +from testcase import ( + QuestionAnsweringTest, + GlobalQuestionAnsweringAccountPreparer +) + +from azure.ai.language.questionanswering import QuestionAnsweringClient +from azure.ai.language.questionanswering.rest import * +from azure.ai.language.questionanswering.models import ( + KnowledgebaseQueryParameters, + KnowledgebaseAnswerRequestContext, + AnswerSpanRequest, +) + + +class QnAKnowledgebaseTests(QuestionAnsweringTest): + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_knowledgebase_llc(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + json_content = { + "question": "Ports and connectors", + "top": 3, + "context": { + "previousUserQuery": "Meet Surface Pro 4", + "previousQnAId": 4 + } + } + request = build_query_knowledgebase_request( + json=json_content, + project_name=qna_project, + deployment_name='test' + ) + with client: + response = client.send_request(request) + assert response.status_code == 200 + + output = response.json() + assert output + assert output.get('answers') + for answer in output['answers']: + assert answer.get('answer') + assert answer.get('confidenceScore') + assert answer.get('id') + assert answer.get('source') + assert answer.get('metadata') is not None + assert not answer.get('answerSpan') + + assert answer.get('questions') + for question in answer['questions']: + assert question + + assert answer.get('dialog') + assert answer['dialog'].get('isContextOnly') is not None + assert answer['dialog'].get('prompts') is not None + if answer['dialog'].get('prompts'): + for prompt in answer['dialog']['prompts']: + assert prompt.get('displayOrder') is not None + assert prompt.get('qnaId') + assert prompt.get('displayText') + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_knowledgebase_llc_with_answerspan(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + json_content = { + "question": "Ports and connectors", + "top": 3, + "context": { + "previousUserQuery": "Meet Surface Pro 4", + "previousQnAId": 4 + }, + "answerSpanRequest": { + "enable": True, + "confidenceScoreThreshold": 0.1, + "topAnswersWithSpan": 1 + } + } + request = build_query_knowledgebase_request( + json=json_content, + project_name=qna_project, + deployment_name='test' + ) + with client: + response = client.send_request(request) + assert response.status_code == 200 + + output = response.json() + assert output + assert output.get('answers') + for answer in output['answers']: + assert answer.get('answer') + assert answer.get('confidenceScore') + assert answer.get('id') + assert answer.get('source') + assert answer.get('metadata') is not None + + if answer.get('answerSpan'): + assert answer['answerSpan'].get('text') + assert answer['answerSpan'].get('confidenceScore') + assert answer['answerSpan'].get('offset') is not None + assert answer['answerSpan'].get('length') + + assert answer.get('questions') + for question in answer['questions']: + assert question + + assert answer.get('dialog') + assert answer['dialog'].get('isContextOnly') is not None + assert answer['dialog'].get('prompts') is not None + if answer['dialog'].get('prompts'): + for prompt in answer['dialog']['prompts']: + assert prompt.get('displayOrder') is not None + assert prompt.get('qnaId') + assert prompt.get('displayText') + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_knowledgebase(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + query_params = KnowledgebaseQueryParameters( + question="Ports and connectors", + top=3, + context=KnowledgebaseAnswerRequestContext( + previous_user_query="Meet Surface Pro 4", + previous_qna_id=4 + ) + ) + + with client: + output = client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert output.answers + for answer in output.answers: + assert answer.answer + assert answer.confidence_score + assert answer.id + assert answer.source + assert answer.metadata is not None + assert not answer.answer_span + + assert answer.questions + for question in answer.questions: + assert question + + assert answer.dialog + assert answer.dialog.is_context_only is not None + assert answer.dialog.prompts is not None + if answer.dialog.prompts: + for prompt in answer.dialog.prompts: + assert prompt.display_order is not None + assert prompt.qna_id + assert prompt.display_text + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_knowledgebase_with_answerspan(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + query_params = KnowledgebaseQueryParameters( + question="Ports and connectors", + top=3, + context=KnowledgebaseAnswerRequestContext( + previous_user_query="Meet Surface Pro 4", + previous_qna_id=4 + ), + answer_span_request=AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.1, + top_answers_with_span=2 + ) + ) + + with client: + output = client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert output.answers + for answer in output.answers: + assert answer.answer + assert answer.confidence_score + assert answer.id + assert answer.source + assert answer.metadata is not None + + if answer.answer_span: + assert answer.answer_span.text + assert answer.answer_span.confidence_score + assert answer.answer_span.offset is not None + assert answer.answer_span.length + + assert answer.questions + for question in answer.questions: + assert question + + assert answer.dialog + assert answer.dialog.is_context_only is not None + assert answer.dialog.prompts is not None + if answer.dialog.prompts: + for prompt in answer.dialog.prompts: + assert prompt.display_order is not None + assert prompt.qna_id + assert prompt.display_text + + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_knowledgebase_with_dictparams(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + query_params = { + "question": "How long should my Surface battery last?", + "top": 3, + "userId": "sd53lsY=", + "confidenceScoreThreshold": 0.2, + "answerSpanRequest": { + "enable": True, + "confidenceScoreThreshold": 0.2, + "topAnswersWithSpan": 1 + }, + "includeUnstructuredSources": True + } + + with client: + output = client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert len(output.answers) == 3 + confident_answers = [a for a in output.answers if a.confidence_score > 0.9] + assert len(confident_answers) == 1 + assert confident_answers[0].source == "surface-pro-4-user-guide-EN.pdf" + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_knowledgebase_with_followup(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + with client: + query_params = KnowledgebaseQueryParameters( + question="How long should my Surface battery last?", + top=3, + user_id="sd53lsY=", + confidence_score_threshold=0.2, + answer_span_request=AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + include_unstructured_sources=True + ) + + output = client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + confident_answers = [a for a in output.answers if a.confidence_score > 0.9] + assert len(confident_answers) == 1 + assert confident_answers[0].source == "surface-pro-4-user-guide-EN.pdf" + + query_params = KnowledgebaseQueryParameters( + question="How long it takes to charge Surface?", + top=3, + user_id="sd53lsY=", + confidence_score_threshold=0.2, + context=KnowledgebaseAnswerRequestContext( + previous_user_query="How long should my Surface battery last?", + previous_qna_id=confident_answers[0].id + ), + answer_span_request=AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + include_unstructured_sources=True + ) + output = client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert len(output.answers) == 2 + confident_answers = [a for a in output.answers if a.confidence_score > 0.6] + assert len(confident_answers) == 1 + assert confident_answers[0].answer_span.text == "two to four hours" + + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_knowledgebase_only_id(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + with client: + query_params = KnowledgebaseQueryParameters( + qna_id=19 + ) + + output = client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert len(output.answers) == 1 diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase_async.py new file mode 100644 index 000000000000..0bb798e0ca2f --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_knowledgebase_async.py @@ -0,0 +1,326 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +import os +import pytest + +from azure.core.exceptions import HttpResponseError, ClientAuthenticationError +from azure.core.credentials import AzureKeyCredential + +from testcase import ( + GlobalQuestionAnsweringAccountPreparer +) +from asynctestcase import AsyncQuestionAnsweringTest + +from azure.ai.language.questionanswering.models import ( + KnowledgebaseQueryParameters, + KnowledgebaseAnswerRequestContext, + AnswerSpanRequest, +) +from azure.ai.language.questionanswering.aio import QuestionAnsweringClient +from azure.ai.language.questionanswering.rest import * + + +class QnAKnowledgebaseTestsAsync(AsyncQuestionAnsweringTest): + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase_llc(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + json_content = { + "question": "Ports and connectors", + "top": 3, + "context": { + "previousUserQuery": "Meet Surface Pro 4", + "previousQnAId": 4 + } + } + request = build_query_knowledgebase_request( + json=json_content, + project_name=qna_project, + deployment_name='test' + ) + async with client: + response = await client.send_request(request) + assert response.status_code == 200 + + output = response.json() + assert output + assert output.get('answers') + for answer in output['answers']: + assert answer.get('answer') + assert answer.get('confidenceScore') + assert answer.get('id') + assert answer.get('source') + assert answer.get('metadata') is not None + assert not answer.get('answerSpan') + + assert answer.get('questions') + for question in answer['questions']: + assert question + + assert answer.get('dialog') + assert answer['dialog'].get('isContextOnly') is not None + assert answer['dialog'].get('prompts') is not None + if answer['dialog'].get('prompts'): + for prompt in answer['dialog']['prompts']: + assert prompt.get('displayOrder') is not None + assert prompt.get('qnaId') + assert prompt.get('displayText') + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase_llc_with_answerspan(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + json_content = { + "question": "Ports and connectors", + "top": 3, + "context": { + "previousUserQuery": "Meet Surface Pro 4", + "previousQnAId": 4 + }, + "answerSpanRequest": { + "enable": True, + "confidenceScoreThreshold": 0.1, + "topAnswersWithSpan": 2 + } + } + request = build_query_knowledgebase_request( + json=json_content, + project_name=qna_project, + deployment_name='test' + ) + async with client: + response = await client.send_request(request) + assert response.status_code == 200 + + output = response.json() + assert output + assert output.get('answers') + for answer in output['answers']: + assert answer.get('answer') + assert answer.get('confidenceScore') + assert answer.get('id') + assert answer.get('source') + assert answer.get('metadata') is not None + + if answer.get('answerSpan'): + assert answer['answerSpan'].get('text') + assert answer['answerSpan'].get('confidenceScore') + assert answer['answerSpan'].get('offset') is not None + assert answer['answerSpan'].get('length') + + assert answer.get('questions') + for question in answer['questions']: + assert question + + assert answer.get('dialog') + assert answer['dialog'].get('isContextOnly') is not None + assert answer['dialog'].get('prompts') is not None + if answer['dialog'].get('prompts'): + for prompt in answer['dialog']['prompts']: + assert prompt.get('displayOrder') is not None + assert prompt.get('qnaId') + assert prompt.get('displayText') + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + query_params = KnowledgebaseQueryParameters( + question="Ports and connectors", + top=3, + context=KnowledgebaseAnswerRequestContext( + previous_user_query="Meet Surface Pro 4", + previous_qna_id=4 + ) + ) + + async with client: + output = await client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert output.answers + for answer in output.answers: + assert answer.answer + assert answer.confidence_score + assert answer.id + assert answer.source + assert answer.metadata is not None + assert not answer.answer_span + + assert answer.questions + for question in answer.questions: + assert question + + assert answer.dialog + assert answer.dialog.is_context_only is not None + assert answer.dialog.prompts is not None + if answer.dialog.prompts: + for prompt in answer.dialog.prompts: + assert prompt.display_order is not None + assert prompt.qna_id + assert prompt.display_text + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase_with_answerspan(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + query_params = KnowledgebaseQueryParameters( + question="Ports and connectors", + top=3, + context=KnowledgebaseAnswerRequestContext( + previous_user_query="Meet Surface Pro 4", + previous_qna_id=4 + ), + answer_span_request=AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.1, + top_answers_with_span=2 + ) + ) + + async with client: + output = await client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert output.answers + for answer in output.answers: + assert answer.answer + assert answer.confidence_score + assert answer.id + assert answer.source + assert answer.metadata is not None + + if answer.answer_span: + assert answer.answer_span.text + assert answer.answer_span.confidence_score + assert answer.answer_span.offset is not None + assert answer.answer_span.length + + assert answer.questions + for question in answer.questions: + assert question + + assert answer.dialog + assert answer.dialog.is_context_only is not None + assert answer.dialog.prompts is not None + if answer.dialog.prompts: + for prompt in answer.dialog.prompts: + assert prompt.display_order is not None + assert prompt.qna_id + assert prompt.display_text + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase_with_dictparams(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + query_params = { + "question": "How long should my Surface battery last?", + "top": 3, + "userId": "sd53lsY=", + "confidenceScoreThreshold": 0.2, + "answerSpanRequest": { + "enable": True, + "confidenceScoreThreshold": 0.2, + "topAnswersWithSpan": 1 + }, + "includeUnstructuredSources": True + } + + async with client: + output = await client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert len(output.answers) == 3 + confident_answers = [a for a in output.answers if a.confidence_score > 0.9] + assert len(confident_answers) == 1 + assert confident_answers[0].source == "surface-pro-4-user-guide-EN.pdf" + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase_with_followup(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + async with client: + query_params = KnowledgebaseQueryParameters( + question="How long should my Surface battery last?", + top=3, + user_id="sd53lsY=", + confidence_score_threshold=0.2, + answer_span_request=AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + include_unstructured_sources=True + ) + + output = await client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + confident_answers = [a for a in output.answers if a.confidence_score > 0.9] + assert len(confident_answers) == 1 + assert confident_answers[0].source == "surface-pro-4-user-guide-EN.pdf" + + query_params = KnowledgebaseQueryParameters( + question="How long it takes to charge Surface?", + top=3, + user_id="sd53lsY=", + confidence_score_threshold=0.2, + context=KnowledgebaseAnswerRequestContext( + previous_user_query="How long should my Surface battery last?", + previous_qna_id=confident_answers[0].id + ), + answer_span_request=AnswerSpanRequest( + enable=True, + confidence_score_threshold=0.2, + top_answers_with_span=1 + ), + include_unstructured_sources=True + ) + output = await client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert len(output.answers) == 2 + confident_answers = [a for a in output.answers if a.confidence_score > 0.6] + assert len(confident_answers) == 1 + assert confident_answers[0].answer_span.text == "two to four hours" + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase_only_id(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + async with client: + query_params = {"qnaId": 19} + + output = await client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + + assert len(output.answers) == 1 + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_knowledgebase_bad_request(self, qna_account, qna_key, qna_project): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + async with client: + query_params = {"qna_id": 19} + + with pytest.raises(HttpResponseError): + await client.query_knowledgebase( + project_name=qna_project, + deployment_name='test', + knowledgebase_query_parameters=query_params + ) + diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text.py new file mode 100644 index 000000000000..9993ae313f6f --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text.py @@ -0,0 +1,126 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from azure.core.exceptions import HttpResponseError, ClientAuthenticationError +from azure.core.credentials import AzureKeyCredential + +from testcase import ( + QuestionAnsweringTest, + GlobalQuestionAnsweringAccountPreparer +) + +from azure.ai.language.questionanswering import QuestionAnsweringClient +from azure.ai.language.questionanswering.rest import * +from azure.ai.language.questionanswering.models import ( + TextQueryParameters, + TextInput +) + +class QnATests(QuestionAnsweringTest): + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_text_llc(self, qna_account, qna_key): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + json_content = { + "question": "What is the meaning of life?", + "records": [ + { + "text": "abc Graphics Surprise, surprise -- our 4K ", + "id": "doc1" + }, + { + "text": "e graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on ", + "id": "doc2" + }, + { + "text": "Graphics Surprise, surprise -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on the MX250 model, which is well above our 30-fps playability, the category average (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA (45 fps) fell flat on this real-world test but ran better than the base model Envy 13 (31 fps). Audio I had a good ol' time groovin' to the sound of the Envy 13's crisp speakers. HP went all out with the Envy, placing dual speakers on the underside of the chassis along with a third, top-firing driver above the keyboard. Devon Gilfillian's funky jam \"Here and Now\" boomed smooth, soulful tunes throughout my small apartment. The twang of the electric guitar played nicely with the thudding percussion but never overshadowed Gilfillian or the female backup vocals. Bang & Olufsen software comes preinstalled on the Envy 13, with equalizer controls so you can adjust the bass, midrange and treble to your liking. But even out of the box, you'll enjoy great sound without having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p non-touch display if battery life is important to you. The FHD model endured for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 minutes on our battery test, which involves continuous web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but powered down long before the 1080p version. Webcam The 720p webcam on the Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room was covered in a haze of visual noise. My beard and hair were unkempt blobs, while my eyes looked like they were drawn on by a pointillist painter. If there's one positive, it's that the lens captures natural colors and even extracted the different shades of gray in my T-shirt. On the right edge of the Envy 13 is a physical kill switch that cuts the power to the webcam so you can feel reassured that nobody is snooping on you. Heat Leave the lapdesk at home - you don't have to worry about the Envy 13 overheating. After I played a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) and underside (90 degrees) also remained well below our 95-degree comfort threshold. Even the toastiest part of the machine, the lower-left edge on the underside, topped out at 94 degrees. Software and Warranty It's a shame that a laptop with such beautiful hardware ships with such ugly software. Pre-installed on this machine are entirely too many programs that could either be packaged together or omitted altogether. HP provides an app called Audio Switch, which simply lets you switch your audio input/output between the internal speakers and headphones. As the same implies, HP's Command Center is where you can get information about your Envy 13 but also switch the thermal profiles between comfort and performance. Along with support documentation, HP also bundles in a setup program called JumpStart, a program for connecting printers and a redundant system-info app called Event Utility. Also installed on the Envy 13's Windows 10 Home OS are several Microsoft apps, including Simple Solitaire, Candy Crush Friends and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee Security. HP ships the Envy 13 with a one-year warranty. See how HP did on our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The Envy 13 has cemented its standing as the ultimate laptop for college students or travelers. Along with 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. In many ways, the Envy 13 is what we wanted the new MacBook Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air would be: fast, attractive and affordable. Just be sure to buy the right model. We strongly recommend the 1080p version over the 4K model because it lasts several hours longer on a charge and costs less. In fact, if we were reviewing the 4K model separately, we'd only give it a 3.5 rating. You should also consider the Envy 13 with a 10th Gen CPU, although we haven't gotten the chance to review it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of many good options. We also recommend the Samsung Notebook 9 Pro, which has a similarly premium design but much better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another recommended alternative, though you might want to wait a few months for the rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop that checks all the right boxes --- as long as you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel Wireless-AC 9560 ", + "id": "doc3" + } + ], + "language": "en" + } + request = build_query_text_request( + json=json_content + ) + response = client.send_request(request) + assert response.status_code == 200 + + output = response.json() + assert output.get('answers') + for answer in output['answers']: + assert answer.get('answer') + assert answer.get('confidenceScore') + assert answer.get('id') + assert answer.get('offset') + assert answer.get('length') + assert answer.get('answerSpan') + assert answer['answerSpan'].get('text') + assert answer['answerSpan'].get('confidenceScore') + assert answer['answerSpan'].get('offset') is not None + assert answer['answerSpan'].get('length') + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_text(self, qna_account, qna_key): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + params = TextQueryParameters( + question="What is the meaning of life?", + records=[ + TextInput( + text="abc Graphics Surprise, surprise -- our 4K ", + id="doc1" + ), + TextInput( + text="e graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on ", + id="doc2" + ), + TextInput( + text="Graphics Surprise, surprise -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on the MX250 model, which is well above our 30-fps playability, the category average (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA (45 fps) fell flat on this real-world test but ran better than the base model Envy 13 (31 fps). Audio I had a good ol' time groovin' to the sound of the Envy 13's crisp speakers. HP went all out with the Envy, placing dual speakers on the underside of the chassis along with a third, top-firing driver above the keyboard. Devon Gilfillian's funky jam \"Here and Now\" boomed smooth, soulful tunes throughout my small apartment. The twang of the electric guitar played nicely with the thudding percussion but never overshadowed Gilfillian or the female backup vocals. Bang & Olufsen software comes preinstalled on the Envy 13, with equalizer controls so you can adjust the bass, midrange and treble to your liking. But even out of the box, you'll enjoy great sound without having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p non-touch display if battery life is important to you. The FHD model endured for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 minutes on our battery test, which involves continuous web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but powered down long before the 1080p version. Webcam The 720p webcam on the Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room was covered in a haze of visual noise. My beard and hair were unkempt blobs, while my eyes looked like they were drawn on by a pointillist painter. If there's one positive, it's that the lens captures natural colors and even extracted the different shades of gray in my T-shirt. On the right edge of the Envy 13 is a physical kill switch that cuts the power to the webcam so you can feel reassured that nobody is snooping on you. Heat Leave the lapdesk at home - you don't have to worry about the Envy 13 overheating. After I played a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) and underside (90 degrees) also remained well below our 95-degree comfort threshold. Even the toastiest part of the machine, the lower-left edge on the underside, topped out at 94 degrees. Software and Warranty It's a shame that a laptop with such beautiful hardware ships with such ugly software. Pre-installed on this machine are entirely too many programs that could either be packaged together or omitted altogether. HP provides an app called Audio Switch, which simply lets you switch your audio input/output between the internal speakers and headphones. As the same implies, HP's Command Center is where you can get information about your Envy 13 but also switch the thermal profiles between comfort and performance. Along with support documentation, HP also bundles in a setup program called JumpStart, a program for connecting printers and a redundant system-info app called Event Utility. Also installed on the Envy 13's Windows 10 Home OS are several Microsoft apps, including Simple Solitaire, Candy Crush Friends and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee Security. HP ships the Envy 13 with a one-year warranty. See how HP did on our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The Envy 13 has cemented its standing as the ultimate laptop for college students or travelers. Along with 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. In many ways, the Envy 13 is what we wanted the new MacBook Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air would be: fast, attractive and affordable. Just be sure to buy the right model. We strongly recommend the 1080p version over the 4K model because it lasts several hours longer on a charge and costs less. In fact, if we were reviewing the 4K model separately, we'd only give it a 3.5 rating. You should also consider the Envy 13 with a 10th Gen CPU, although we haven't gotten the chance to review it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of many good options. We also recommend the Samsung Notebook 9 Pro, which has a similarly premium design but much better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another recommended alternative, though you might want to wait a few months for the rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop that checks all the right boxes --- as long as you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel Wireless-AC 9560 ", + id="doc3" + ) + ], + language="en" + ) + + output = client.query_text(params) + assert output.answers + for answer in output.answers: + assert answer.answer + assert answer.confidence_score + assert answer.id + assert answer.offset + assert answer.length + assert answer.answer_span + assert answer.answer_span.text + assert answer.answer_span.confidence_score + assert answer.answer_span.offset is not None + assert answer.answer_span.length + + @GlobalQuestionAnsweringAccountPreparer() + def test_query_text_with_dictparams(self, qna_account, qna_key): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + params = { + "question": "How long it takes to charge surface?", + "records": [ + { + "text": "Power and charging. It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. " + + "It can take longer if you’re using your Surface for power-intensive activities like gaming or video streaming while you’re charging it.", + "id": "1" + }, + { + "text": "You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. "+ + "The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface.", + "id": "2" + } + ], + "language": "en" + } + + with client: + output = client.query_text(params) + assert len(output.answers) == 3 + confident_answers = [a for a in output.answers if a.confidence_score > 0.9] + assert len(confident_answers) == 2 + assert confident_answers[0].answer_span.text == "two to four hours" diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text_async.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text_async.py new file mode 100644 index 000000000000..4a04f2ac5613 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/test_query_text_async.py @@ -0,0 +1,128 @@ +# coding=utf-8 +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from azure.core.exceptions import HttpResponseError, ClientAuthenticationError +from azure.core.credentials import AzureKeyCredential + +from testcase import ( + QuestionAnsweringTest, + GlobalQuestionAnsweringAccountPreparer +) + +from azure.ai.language.questionanswering.aio import QuestionAnsweringClient +from azure.ai.language.questionanswering.rest import * +from azure.ai.language.questionanswering.models import ( + TextQueryParameters, + TextInput +) + +class QnATests(QuestionAnsweringTest): + def setUp(self): + super(QnATests, self).setUp() + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_text_llc(self, qna_account, qna_key): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + json_content = { + "question": "What is the meaning of life?", + "records": [ + { + "text": "abc Graphics Surprise, surprise -- our 4K ", + "id": "doc1" + }, + { + "text": "e graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on ", + "id": "doc2" + }, + { + "text": "Graphics Surprise, surprise -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on the MX250 model, which is well above our 30-fps playability, the category average (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA (45 fps) fell flat on this real-world test but ran better than the base model Envy 13 (31 fps). Audio I had a good ol' time groovin' to the sound of the Envy 13's crisp speakers. HP went all out with the Envy, placing dual speakers on the underside of the chassis along with a third, top-firing driver above the keyboard. Devon Gilfillian's funky jam \"Here and Now\" boomed smooth, soulful tunes throughout my small apartment. The twang of the electric guitar played nicely with the thudding percussion but never overshadowed Gilfillian or the female backup vocals. Bang & Olufsen software comes preinstalled on the Envy 13, with equalizer controls so you can adjust the bass, midrange and treble to your liking. But even out of the box, you'll enjoy great sound without having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p non-touch display if battery life is important to you. The FHD model endured for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 minutes on our battery test, which involves continuous web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but powered down long before the 1080p version. Webcam The 720p webcam on the Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room was covered in a haze of visual noise. My beard and hair were unkempt blobs, while my eyes looked like they were drawn on by a pointillist painter. If there's one positive, it's that the lens captures natural colors and even extracted the different shades of gray in my T-shirt. On the right edge of the Envy 13 is a physical kill switch that cuts the power to the webcam so you can feel reassured that nobody is snooping on you. Heat Leave the lapdesk at home - you don't have to worry about the Envy 13 overheating. After I played a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) and underside (90 degrees) also remained well below our 95-degree comfort threshold. Even the toastiest part of the machine, the lower-left edge on the underside, topped out at 94 degrees. Software and Warranty It's a shame that a laptop with such beautiful hardware ships with such ugly software. Pre-installed on this machine are entirely too many programs that could either be packaged together or omitted altogether. HP provides an app called Audio Switch, which simply lets you switch your audio input/output between the internal speakers and headphones. As the same implies, HP's Command Center is where you can get information about your Envy 13 but also switch the thermal profiles between comfort and performance. Along with support documentation, HP also bundles in a setup program called JumpStart, a program for connecting printers and a redundant system-info app called Event Utility. Also installed on the Envy 13's Windows 10 Home OS are several Microsoft apps, including Simple Solitaire, Candy Crush Friends and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee Security. HP ships the Envy 13 with a one-year warranty. See how HP did on our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The Envy 13 has cemented its standing as the ultimate laptop for college students or travelers. Along with 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. In many ways, the Envy 13 is what we wanted the new MacBook Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air would be: fast, attractive and affordable. Just be sure to buy the right model. We strongly recommend the 1080p version over the 4K model because it lasts several hours longer on a charge and costs less. In fact, if we were reviewing the 4K model separately, we'd only give it a 3.5 rating. You should also consider the Envy 13 with a 10th Gen CPU, although we haven't gotten the chance to review it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of many good options. We also recommend the Samsung Notebook 9 Pro, which has a similarly premium design but much better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another recommended alternative, though you might want to wait a few months for the rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop that checks all the right boxes --- as long as you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel Wireless-AC 9560 ", + "id": "doc3" + } + ], + "language": "en" + } + request = build_query_text_request( + json=json_content + ) + response = await client.send_request(request) + assert response.status_code == 200 + + output = response.json() + assert output.get('answers') + for answer in output['answers']: + assert answer.get('answer') + assert answer.get('confidenceScore') + assert answer.get('id') + assert answer.get('offset') + assert answer.get('length') + assert answer.get('answerSpan') + assert answer['answerSpan'].get('text') + assert answer['answerSpan'].get('confidenceScore') + assert answer['answerSpan'].get('offset') is not None + assert answer['answerSpan'].get('length') + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_text(self, qna_account, qna_key): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + params = TextQueryParameters( + question="What is the meaning of life?", + records=[ + TextInput( + text="abc Graphics Surprise, surprise -- our 4K ", + id="doc1" + ), + TextInput( + text="e graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on ", + id="doc2" + ), + TextInput( + text="Graphics Surprise, surprise -- our 4K Envy 13 came with a discrete graphics card. While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. The MX250-equipped Envy 13 scored a 116,575 on the Ice Storm Unlimited benchmark while the base model scored a 82,270. Upgrading to the discrete graphics gives the Envy 13 better performance than the Notebook 9 Pro (61,662; UHD 620), Surface Laptop 2 (71,647; UHD 620) and the premium laptop average (86,937). While the Nvidia GeForce MX250 GPU isn't meant for demanding gaming, it is a step up from integrated graphics as proven by comparing it to the UHD 620 GPU in the FHD model. We played the racing game Dirt 3 at 92 frames per second on the MX250 model, which is well above our 30-fps playability, the category average (69 fps) and what the Surface Laptop 2 (82 fps) achieved. The ZenBook S UX391UA (45 fps) fell flat on this real-world test but ran better than the base model Envy 13 (31 fps). Audio I had a good ol' time groovin' to the sound of the Envy 13's crisp speakers. HP went all out with the Envy, placing dual speakers on the underside of the chassis along with a third, top-firing driver above the keyboard. Devon Gilfillian's funky jam \"Here and Now\" boomed smooth, soulful tunes throughout my small apartment. The twang of the electric guitar played nicely with the thudding percussion but never overshadowed Gilfillian or the female backup vocals. Bang & Olufsen software comes preinstalled on the Envy 13, with equalizer controls so you can adjust the bass, midrange and treble to your liking. But even out of the box, you'll enjoy great sound without having to bust out your headphones. Battery Life Get an Envy 13 with the 1080p non-touch display if battery life is important to you. The FHD model endured for 11 hours and 11 minutes whereas the 4K model lasted only 4 hours and 36 minutes on our battery test, which involves continuous web browsing over Wi-Fi at 150 nits of brightness. MORE: Laptops with Best Battery Life - Longest Lasting Laptop Batteries Competing laptops like the ZenBook S UX391UA (7:05), Surface Laptop 2 (9:22) and Notebook 9 Pro (8:53) outstayed the 4K Envy 13 but powered down long before the 1080p version. Webcam The 720p webcam on the Envy 13 is nothing to write home about. A selfie I snapped in my dimly lit room was covered in a haze of visual noise. My beard and hair were unkempt blobs, while my eyes looked like they were drawn on by a pointillist painter. If there's one positive, it's that the lens captures natural colors and even extracted the different shades of gray in my T-shirt. On the right edge of the Envy 13 is a physical kill switch that cuts the power to the webcam so you can feel reassured that nobody is snooping on you. Heat Leave the lapdesk at home - you don't have to worry about the Envy 13 overheating. After I played a 15-minute, full-HD video in full screen, the touchpad on the HP Envy 13 with a Core i7 CPU rose to only 83 degrees Fahrenheit while the keyboard (87 degrees) and underside (90 degrees) also remained well below our 95-degree comfort threshold. Even the toastiest part of the machine, the lower-left edge on the underside, topped out at 94 degrees. Software and Warranty It's a shame that a laptop with such beautiful hardware ships with such ugly software. Pre-installed on this machine are entirely too many programs that could either be packaged together or omitted altogether. HP provides an app called Audio Switch, which simply lets you switch your audio input/output between the internal speakers and headphones. As the same implies, HP's Command Center is where you can get information about your Envy 13 but also switch the thermal profiles between comfort and performance. Along with support documentation, HP also bundles in a setup program called JumpStart, a program for connecting printers and a redundant system-info app called Event Utility. Also installed on the Envy 13's Windows 10 Home OS are several Microsoft apps, including Simple Solitaire, Candy Crush Friends and Your Phone. Other third-party apps include Booking.com, Netflix and McAfee Security. HP ships the Envy 13 with a one-year warranty. See how HP did on our Tech Support Showdown and Best and Worst Brands ranking. Bottom Line The Envy 13 has cemented its standing as the ultimate laptop for college students or travelers. Along with 11-plus hours of battery life (on the FHD model), the Envy 13 has a sleek, ultraportable chassis, fast performance, and powerful speakers. Best of all, the Envy 13 starts at a reasonable $799, which is hundreds less than the competition. In many ways, the Envy 13 is what we wanted the new MacBook Air to be. The new HP Envy 13 is everything I was hoping the new MacBook Air would be: fast, attractive and affordable. Just be sure to buy the right model. We strongly recommend the 1080p version over the 4K model because it lasts several hours longer on a charge and costs less. In fact, if we were reviewing the 4K model separately, we'd only give it a 3.5 rating. You should also consider the Envy 13 with a 10th Gen CPU, although we haven't gotten the chance to review it yet. If you absolutely need a high-res display, the 4K Envy 13 is one of many good options. We also recommend the Samsung Notebook 9 Pro, which has a similarly premium design but much better battery life than the 4K Envy. The Microsoft Surface Laptop 2 is another recommended alternative, though you might want to wait a few months for the rumored Surface Laptop 3. Overall, the HP Envy 13 is a fantastic laptop that checks all the right boxes --- as long as you buy the 1080p model. Credit: Laptop Mag HP Envy 13 (2019) Specs BluetoothBluetooth 5.0 BrandHP CPUIntel Core i7-8565U Card SlotsmicroSD Company Websitehttps://www8.hp.com/us/en/home.html Display Size13.3 Graphics CardNvidia GeForce MX250 Hard Drive Size512GB Hard Drive TypePCIe NVMe M.2 Highest Available Resolution3840 x 2160 Native Resolution3840 x 2160 Operating SystemWindows 10 Home Ports (excluding USB)USB 3.1 with Type-C, USB 3.1 Always-On, USB 3.1, Headphone/Mic, microSD RAM16GB RAM Upgradable to16GB Size12.1 x 8.3 x .57 inches Touchpad Size4.3 x 2.2 inches USB Ports3 Video Memory2GB Warranty/Supportone-year warranty. Weight2.8 pounds Wi-Fi802.11ac Wi-Fi ModelIntel Wireless-AC 9560 ", + id="doc3" + ) + ], + language="en" + ) + + output = await client.query_text(params) + assert output.answers + for answer in output.answers: + assert answer.answer + assert answer.confidence_score + assert answer.id + assert answer.offset + assert answer.length + assert answer.answer_span + assert answer.answer_span.text + assert answer.answer_span.confidence_score + assert answer.answer_span.offset is not None + assert answer.answer_span.length + + @GlobalQuestionAnsweringAccountPreparer() + async def test_query_text_with_dictparams(self, qna_account, qna_key): + client = QuestionAnsweringClient(qna_account, AzureKeyCredential(qna_key)) + params = { + "question": "How long it takes to charge surface?", + "records": [ + { + "text": "Power and charging. It takes two to four hours to charge the Surface Pro 4 battery fully from an empty state. " + + "It can take longer if you’re using your Surface for power-intensive activities like gaming or video streaming while you’re charging it.", + "id": "1" + }, + { + "text": "You can use the USB port on your Surface Pro 4 power supply to charge other devices, like a phone, while your Surface charges. "+ + "The USB port on the power supply is only for charging, not for data transfer. If you want to use a USB device, plug it into the USB port on your Surface.", + "id": "2" + } + ], + "language": "en" + } + + async with client: + output = await client.query_text(params) + assert len(output.answers) == 3 + confident_answers = [a for a in output.answers if a.confidence_score > 0.9] + assert len(confident_answers) == 2 + assert confident_answers[0].answer_span.text == "two to four hours" diff --git a/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/testcase.py b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/testcase.py new file mode 100644 index 000000000000..56c4be587ee2 --- /dev/null +++ b/sdk/cognitivelanguage/azure-ai-language-questionanswering/tests/testcase.py @@ -0,0 +1,109 @@ + +# 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. +# -------------------------------------------------------------------------- +import os +import pytest + +from azure.core.credentials import AccessToken, AzureKeyCredential +from devtools_testutils import ( + AzureTestCase, + AzureMgmtPreparer, + FakeResource, + ResourceGroupPreparer, +) +from devtools_testutils.cognitiveservices_testcase import CognitiveServicesAccountPreparer +from azure_devtools.scenario_tests import ReplayableTest + +from azure.ai.language.questionanswering import QuestionAnsweringClient + + +REGION = 'westus2' + + +class FakeTokenCredential(object): + """Protocol for classes able to provide OAuth tokens. + :param str scopes: Lets you specify the type of access needed. + """ + def __init__(self): + self.token = AccessToken("YOU SHALL NOT PASS", 0) + + def get_token(self, *args): + return self.token + +TEST_ENDPOINT = 'https://test-resource.api.cognitive.microsoft.com' +TEST_KEY = '0000000000000000' +TEST_PROJECT = 'test-project' + + +class QuestionAnsweringTest(AzureTestCase): + FILTER_HEADERS = ReplayableTest.FILTER_HEADERS + ['Ocp-Apim-Subscription-Key'] + + def __init__(self, method_name): + super(QuestionAnsweringTest, self).__init__(method_name) + self.scrubber.register_name_pair(os.environ.get("QNA_ACCOUNT"), TEST_ENDPOINT) + self.scrubber.register_name_pair(os.environ.get("QNA_KEY"), TEST_KEY) + self.scrubber.register_name_pair(os.environ.get("QNA_PROJECT"), TEST_PROJECT) + + def get_oauth_endpoint(self): + raise NotImplementedError() + + def generate_oauth_token(self): + if self.is_live: + from azure.identity import ClientSecretCredential + return ClientSecretCredential( + self.get_settings_value("TENANT_ID"), + self.get_settings_value("CLIENT_ID"), + self.get_settings_value("CLIENT_SECRET"), + ) + return self.generate_fake_token() + + def generate_fake_token(self): + return FakeTokenCredential() + + +class GlobalResourceGroupPreparer(AzureMgmtPreparer): + def __init__(self): + super(GlobalResourceGroupPreparer, self).__init__( + name_prefix='', + random_name_length=42 + ) + + def create_resource(self, name, **kwargs): + rg = FakeResource( + name="rgname", + id="/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgname" + ) + + return { + 'location': REGION, + 'resource_group': rg, + } + + +class GlobalQuestionAnsweringAccountPreparer(AzureMgmtPreparer): + def __init__(self): + super(GlobalQuestionAnsweringAccountPreparer, self).__init__( + name_prefix='', + random_name_length=42 + ) + + def create_resource(self, name, **kwargs): + if self.is_live: + return { + 'location': REGION, + 'resource_group': "rgname", + 'qna_account': os.environ.get("QNA_ACCOUNT"), + 'qna_key': os.environ.get("QNA_KEY"), + 'qna_project': os.environ.get("QNA_PROJECT") + } + return { + 'location': REGION, + 'resource_group': "rgname", + 'qna_account': TEST_ENDPOINT, + 'qna_key': TEST_KEY, + 'qna_project': TEST_PROJECT + } diff --git a/sdk/cognitivelanguage/ci.yml b/sdk/cognitivelanguage/ci.yml new file mode 100644 index 000000000000..15f72f532b70 --- /dev/null +++ b/sdk/cognitivelanguage/ci.yml @@ -0,0 +1,35 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. + +trigger: + branches: + include: + - master + - main + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/cognitivelanguage/ + - scripts/ + +pr: + branches: + include: + - master + - main + - feature/* + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/cognitivelanguage/ + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: cognitivelanguage + Artifacts: + - name: azure-ai-language-questionanswering + safeName: questionanswering \ No newline at end of file diff --git a/sdk/cognitivelanguage/tests.yml b/sdk/cognitivelanguage/tests.yml new file mode 100644 index 000000000000..b2b663ad9323 --- /dev/null +++ b/sdk/cognitivelanguage/tests.yml @@ -0,0 +1,19 @@ +trigger: none + +stages: + - template: ../../eng/pipelines/templates/stages/archetype-sdk-tests.yml + parameters: + AllocateResourceGroup: false + ServiceDirectory: cognitivelanguage + MatrixReplace: + - TestSamples=.*/true + EnvVars: + QNA_KEY: $(qna-key) + QNA_PROJECT: 190a9e13-8ede-4e4b-a8fd-c4d7f2aeab6c + QNA_ACCOUNT: $(qna-uri) + AZURE_CLIENT_ID: $(aad-azure-sdk-test-client-id) + AZURE_CLIENT_SECRET: $(aad-azure-sdk-test-client-secret) + AZURE_SUBSCRIPTION_ID: $(azure-subscription-id) + AZURE_TENANT_ID: $(aad-azure-sdk-test-tenant-id) + TEST_MODE: 'RunLiveNoRecord' # use when allowing preparers to create the rgs for you + AZURE_TEST_RUN_LIVE: 'true' # use when utilizing the New-TestResources Script diff --git a/sdk/nspkg/azure-ai-language-nspkg/CHANGELOG.md b/sdk/nspkg/azure-ai-language-nspkg/CHANGELOG.md new file mode 100644 index 000000000000..b9f7cb3c5975 --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release History + +## 1.0.0 (unreleased) diff --git a/sdk/nspkg/azure-ai-language-nspkg/MANIFEST.in b/sdk/nspkg/azure-ai-language-nspkg/MANIFEST.in new file mode 100644 index 000000000000..c42c90b08fae --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/MANIFEST.in @@ -0,0 +1,4 @@ +include *.md +include azure/__init__.py +include azure/ai/__init__.py +include azure/ai/language/__init__.py \ No newline at end of file diff --git a/sdk/nspkg/azure-ai-language-nspkg/README.md b/sdk/nspkg/azure-ai-language-nspkg/README.md new file mode 100644 index 000000000000..2195523dfff8 --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/README.md @@ -0,0 +1,16 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure ai-language Services namespace package. + +This package is not intended to be installed directly by the end user. + +Since version 3.0, this is Python 2 package only, Python 3.x SDKs will use `PEP420 ` as namespace package strategy. +To avoid issues with package servers that does not support `python_requires`, a Python 3 package is installed but is empty. + +It provides the necessary files for other packages to extend the azure.ai namespace. + +If you are looking to install the Azure client libraries, see the +`azure `__ bundle package. + + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Ftextanalytics%2Fazure-ai-nspkg%2FREADME.png) \ No newline at end of file diff --git a/sdk/nspkg/azure-ai-language-nspkg/azure/__init__.py b/sdk/nspkg/azure-ai-language-nspkg/azure/__init__.py new file mode 100644 index 000000000000..69e3be50dac4 --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/nspkg/azure-ai-language-nspkg/azure/ai/__init__.py b/sdk/nspkg/azure-ai-language-nspkg/azure/ai/__init__.py new file mode 100644 index 000000000000..69e3be50dac4 --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/azure/ai/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/nspkg/azure-ai-language-nspkg/azure/ai/language/__init__.py b/sdk/nspkg/azure-ai-language-nspkg/azure/ai/language/__init__.py new file mode 100644 index 000000000000..69e3be50dac4 --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/azure/ai/language/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) diff --git a/sdk/nspkg/azure-ai-language-nspkg/sdk_packaging.toml b/sdk/nspkg/azure-ai-language-nspkg/sdk_packaging.toml new file mode 100644 index 000000000000..e7687fdae93b --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/sdk_packaging.toml @@ -0,0 +1,2 @@ +[packaging] +auto_update = false \ No newline at end of file diff --git a/sdk/nspkg/azure-ai-language-nspkg/setup.py b/sdk/nspkg/azure-ai-language-nspkg/setup.py new file mode 100644 index 000000000000..eff37c87d84a --- /dev/null +++ b/sdk/nspkg/azure-ai-language-nspkg/setup.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +#------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +#-------------------------------------------------------------------------- +import sys +from setuptools import setup + +# azure v0.x is not compatible with this package +# azure v0.x used to have a __version__ attribute (newer versions don't) +try: + import azure + try: + ver = azure.__version__ + raise Exception( + 'This package is incompatible with azure=={}. '.format(ver) + + 'Uninstall it with "pip uninstall azure".' + ) + except AttributeError: + pass +except ImportError: + pass + +PACKAGES = [] +# Do an empty package on Python 3 and not python_requires, since not everybody is ready +# https://github.com/Azure/azure-sdk-for-python/issues/3447 +# https://github.com/Azure/azure-sdk-for-python/issues/3481 +if sys.version_info[0] < 3: + PACKAGES = ['azure.ai.language'] + +setup( + name='azure-ai-language-nspkg', + version='1.0.0', + description='Microsoft Azure ai-language Namespace Package [Internal]', + long_description=open('README.md', 'r').read(), + license='MIT License', + author='Microsoft Corporation', + author_email='azpysdkhelp@microsoft.com', + url='https://github.com/Azure/azure-sdk-for-python', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'License :: OSI Approved :: MIT License', + ], + zip_safe=False, + packages=PACKAGES, + install_requires=[ + 'azure-ai-nspkg>=1.0.0' + ] +) diff --git a/shared_requirements.txt b/shared_requirements.txt index 15a4b91a2f75..a3264e0da86e 100644 --- a/shared_requirements.txt +++ b/shared_requirements.txt @@ -1,5 +1,6 @@ azure-ai-nspkg azure-ai-translation-nspkg +azure-ai-language-nspkg azure-iot-nspkg azure-monitor-nspkg azure-applicationinsights~=0.1.0 @@ -145,6 +146,8 @@ pyjwt>=1.7.1 #override azure-keyvault-secrets azure-core<2.0.0,>=1.7.0 #override azure-ai-textanalytics msrest>=0.6.21 #override azure-ai-textanalytics azure-core<2.0.0,>=1.14.0 +#override azure-ai-language-questionanswering azure-core<2.0.0,>=1.16.0 +#override azure-ai-language-questionanswering msrest>=0.6.21 #override azure-search-documents azure-core<2.0.0,>=1.14.0 #override azure-ai-formrecognizer msrest>=0.6.21 #override azure-ai-formrecognizer azure-core<2.0.0,>=1.8.2