azure.ai.language.questionanswering package

class azure.ai.language.questionanswering.QuestionAnsweringClient(endpoint: str, credential: Union[azure.core.credentials.AzureKeyCredential, azure.core.credentials.TokenCredential], **kwargs: Any)[source]

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 https://learn.microsoft.com/azure/cognitive-services/language-service/overview

Parameters
  • endpoint (str) – Supported Cognitive Services endpoint (e.g., https://<resource-name>.cognitiveservices.azure.com).

  • credential (AzureKeyCredential or TokenCredential) – Credential needed for the client to connect to Azure. This can be the an instance of AzureKeyCredential if using a Language API key or a token credential from azure.identity.

Keyword Arguments
  • default_language (str) – Sets the default language to use for all operations.

  • api_version (str) – Api Version. Default value is “2021-10-01”. Note that overriding this default value may result in unsupported behavior.

close()None[source]
get_answers(*args: azure.ai.language.questionanswering.models._models.AnswersOptions, **kwargs: Any)azure.ai.language.questionanswering.models._models.AnswersResult

Answers the specified question using your knowledge base.

Parameters

options (AnswersOptions) – Positional only. POST body of the request. Provide either options, OR individual keyword arguments. If both are provided, only the options object will be used.

Keyword Arguments
  • project_name (str) – The name of the knowledge base project to use.

  • deployment_name (str) – The name of the specific deployment of the project to use.

  • qna_id (int) – Exact QnA ID to fetch from the knowledge base, this field takes priority over question.

  • question (str) – User question to query against the knowledge base.

  • top (int) – Max number of answers to be returned for the question.

  • user_id (str) – Unique identifier for the user.

  • confidence_threshold (float) – Minimum threshold score for answers, value ranges from 0 to 1.

  • answer_context (KnowledgeBaseAnswerContext) – Context object with previous QnA’s information.

  • ranker_kind (str) – Type of ranker to be used. Possible values include: “Default”, “QuestionOnly”.

  • filters (QueryFilters) – Filter QnAs based on given metadata list and knowledge base sources.

  • short_answer_options (ShortAnswerOptions) – To configure Answer span prediction feature.

  • include_unstructured_sources (bool) – (Optional) Flag to enable Query over Unstructured Sources.

Returns

AnswersResult

Return type

AnswersResult

Raises

HttpResponseError

Example:

Answer the specified question using your knowledge base.
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"]
knowledge_base_project = os.environ["AZURE_QUESTIONANSWERING_PROJECT"]

client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key))
with client:
    question="How long should my Surface battery last?"
    output = client.get_answers(
        question=question,
        top=3,
        confidence_threshold=0.2,
        include_unstructured_sources=True,
        short_answer_options=qna.ShortAnswerOptions(
            confidence_threshold=0.2,
            top=1
        ),
        project_name=knowledge_base_project,
        deployment_name="test"
    )
    best_candidate = [a for a in output.answers if a.confidence > 0.7][0]
    print("Q: {}".format(question))
    print("A: {}".format(best_candidate.answer))

get_answers_from_text(*args: azure.ai.language.questionanswering.models._patch.AnswersFromTextOptions, **kwargs: Any)azure.ai.language.questionanswering.models._models.AnswersFromTextResult

Answers the specified question using the provided text in the body.

Parameters

options (AnswersFromTextOptions) – Positional only. POST body of the request. Provide either options, OR individual keyword arguments. If both are provided, only the options object will be used.

Keyword Arguments
  • question (str) – User question to query against the given text records.

  • text_documents (list[str or TextDocument]) – Text records to be searched for given question.

  • language (str) – 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.

Returns

AnswersFromTextResult

Return type

AnswersFromTextResult

Raises

HttpResponseError

Example:

Answers the specified question using the provided 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:
    question="How long it takes to charge surface?"
    input = qna.AnswersFromTextOptions(
        question=question,
        text_documents=[
            "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.",
            "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.",
        ]
    )

    output = client.get_answers_from_text(input)

    best_answer = [a for a in output.answers if a.confidence > 0.9][0]
    print(u"Q: {}".format(question))
    print(u"A: {}".format(best_answer.answer))

send_request(request: azure.core.rest._rest_py3.HttpRequest, **kwargs: Any)azure.core.rest._rest_py3.HttpResponse[source]

Runs the network request through the client’s chained policies.

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

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

Parameters

request (HttpRequest) – The network request you want to make. Required.

Keyword Arguments

stream (bool) – Whether the response payload will be streamed. Defaults to False.

Returns

The response of your network call. Does not do error handling on your response.

Return type

HttpResponse