Package: azure-ai-language-questionanswering
Azure Cognitive Language Service Question Answering client library for PythonQuestion 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|Package (PyPI)|API reference documentation|Product documentation|SamplesDisclaimerAzure SDK Python packages support for Python 2.7 ended 01 January 2022. For more information and questions, please refer tohttps://github.com/Azure/azure-sdk-for-python/issues/20691Getting startedPrerequisitesPython 3.7 or later is required to use this package.AnAzure subscriptionALanguage ServiceresourceInstall the packageInstall the Azure Question Answering client library for Python withpip:pipinstallazure-ai-language-questionansweringNote: this version of the client library defaults to the service API version2021-10-01.Authenticate the clientIn order to interact with the Question Answering service, you'll need to create an instance of theQuestionAnsweringClientclass or an instance of theAuthoringClientfor managing projects within your resource. You will need anendpoint, and anAPI keyto instantiate a client object. For more information regarding authenticating with Cognitive Services, seeAuthenticate requests to Azure Cognitive Services.Get an API keyYou can get theendpointand anAPI keyfrom the Language resource in theAzure Portal.Alternatively, use theAzure CLIcommand shown below to get the API key from the Language resource.azcognitiveservicesaccountkeyslist--resource-group<resource-group-name>--name<resource-name>Create QuestionAnsweringClientOnce you've determined yourendpointandAPI keyyou can instantiate aQuestionAnsweringClient:fromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionansweringimportQuestionAnsweringClientendpoint="https://{myaccount}.api.cognitive.microsoft.com"credential=AzureKeyCredential("{api-key}")client=QuestionAnsweringClient(endpoint,credential)Create AuthoringClientWith your endpoint and API key, you can instantiate aAuthoringClient:fromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionanswering.authoringimportAuthoringClientendpoint="https://{myaccount}.api.cognitive.microsoft.com"credential=AzureKeyCredential("{api-key}")client=AuthoringClient(endpoint,credential)Create a client with an Azure Active Directory CredentialTo use anAzure Active Directory (AAD) token credential,
provide an instance of the desired credential type obtained from theazure-identitylibrary.
Note that regional endpoints do not support AAD authentication. Create acustom subdomainname for your resource in order to use this type of authentication.Authentication with AAD requires some initial setup:Install azure-identityRegister a new AAD applicationGrant accessto the Language service by assigning the "Cognitive Services Language Reader" role to your service principal.After setup, you can choose which type ofcredentialfrom azure.identity to use.
As an example,DefaultAzureCredentialcan be used to authenticate the client:Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:AZURE_CLIENT_ID,AZURE_TENANT_ID,AZURE_CLIENT_SECRETUse the returned token credential to authenticate the client:fromazure.ai.language.questionansweringimportQuestionAnsweringClientfromazure.identityimportDefaultAzureCredentialcredential=DefaultAzureCredential()client=QuestionAnsweringClient(endpoint="https://<my-custom-subdomain>.cognitiveservices.azure.com/",credential=credential)Key conceptsQuestionAnsweringClientTheQuestionAnsweringClientis 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 asyncQuestionAnsweringClientis in theazure.ai.language.questionanswering.aionamespace.AuthoringClientTheAuthoringClientprovides an interface for managing Question Answering projects. Examples of the available operations include creating and deploying projects, updating your knowledge sources, and updating question and answer pairs. It provides both synchronous and asynchronous APIs.ExamplesQuestionAnsweringClientTheazure-ai-language-questionansweringclient library provides both synchronous and asynchronous APIs.Ask a questionAsk a follow-up questionCreate a new projectAdd a knowledge sourceDeploy your projectAsynchronous operationsAsk a questionThe only input required to ask a question using a knowledge base is just the question itself:importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionansweringimportQuestionAnsweringClientendpoint=os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]key=os.environ["AZURE_QUESTIONANSWERING_KEY"]client=QuestionAnsweringClient(endpoint,AzureKeyCredential(key))output=client.get_answers(question="How long should my Surface battery last?",project_name="FAQ",deployment_name="test")forcandidateinoutput.answers:print("({}){}".format(candidate.confidence,candidate.answer))print("Source:{}".format(candidate.source))You can set additional keyword options to limit the number of answers, specify a minimum confidence score, and more.Ask a follow-up questionIf your knowledge base is configured forchit-chat, the answers from the knowledge base may include suggestedprompts for follow-up questionsto initiate a conversation. You can ask a follow-up question by providing the ID of your chosen answer as the context for the continued conversation:importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionansweringimportQuestionAnsweringClientfromazure.ai.language.questionansweringimportmodelsendpoint=os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]key=os.environ["AZURE_QUESTIONANSWERING_KEY"]client=QuestionAnsweringClient(endpoint,AzureKeyCredential(key))output=client.get_answers(question="How long should charging take?",answer_context=models.KnowledgeBaseAnswerContext(previous_qna_id=previous_answer.qna_id),project_name="FAQ",deployment_name="live")forcandidateinoutput.answers:print("({}){}".format(candidate.confidence,candidate.answer))print("Source:{}".format(candidate.source))Create a new projectimportosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionanswering.authoringimportAuthoringClient# get service secretsendpoint=os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]key=os.environ["AZURE_QUESTIONANSWERING_KEY"]# create clientclient=AuthoringClient(endpoint,AzureKeyCredential(key))withclient:# create projectproject_name="IssacNewton"project=client.create_project(project_name=project_name,options={"description":"biography of Sir Issac Newton","language":"en","multilingualResource":True,"settings":{"defaultAnswer":"no answer"}})print("view created project info:")print("\tname:{}".format(project["projectName"]))print("\tlanguage:{}".format(project["language"]))print("\tdescription:{}".format(project["description"]))Add a knowledge sourceimportosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionanswering.authoringimportAuthoringClient# get service secretsendpoint=os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]key=os.environ["AZURE_QUESTIONANSWERING_KEY"]# create clientclient=AuthoringClient(endpoint,AzureKeyCredential(key))project_name="IssacNewton"update_sources_poller=client.begin_update_sources(project_name=project_name,sources=[{"op":"add","value":{"displayName":"Issac Newton Bio","sourceUri":"https://wikipedia.org/wiki/Isaac_Newton","sourceKind":"url"}}])update_sources_poller.result()# list sourcesprint("list project sources")sources=client.list_sources(project_name=project_name)forsourceinsources:print("project:{}".format(source["displayName"]))print("\tsource:{}".format(source["source"]))print("\tsource Uri:{}".format(source["sourceUri"]))print("\tsource kind:{}".format(source["sourceKind"]))Deploy your projectimportosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionanswering.authoringimportAuthoringClient# get service secretsendpoint=os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]key=os.environ["AZURE_QUESTIONANSWERING_KEY"]# create clientclient=AuthoringClient(endpoint,AzureKeyCredential(key))project_name="IssacNewton"# deploy projectdeployment_poller=client.begin_deploy_project(project_name=project_name,deployment_name="production")deployment_poller.result()# list all deploymentsdeployments=client.list_deployments(project_name=project_name)print("view project deployments")fordindeployments:print(d)Asynchronous operationsThe above examples can also be run asynchronously using the clients in theaionamespace:importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.language.questionanswering.aioimportQuestionAnsweringClientendpoint=os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]key=os.environ["AZURE_QUESTIONANSWERING_KEY"]client=QuestionAnsweringClient(endpoint,AzureKeyCredential(key))output=awaitclient.get_answers(question="How long should my Surface battery last?",project_name="FAQ",deployment_name="production")Optional ConfigurationOptional keyword arguments can be passed in at the client and per-operation level. The azure-corereference documentationdescribes available configurations for retries, logging, transport protocols, and more.TroubleshootingGeneralAzure Question Answering clients raise exceptions defined inAzure Core.
When you interact with the Cognitive Language Service Question Answering client library using the Python SDK, errors returned by the service correspond to the same HTTP status codes returned forREST APIrequests.For example, if you submit a question to a non-existent knowledge base, a400error is returned indicating "Bad Request".fromazure.core.exceptionsimportHttpResponseErrortry:client.get_answers(question="Why?",project_name="invalid-knowledge-base",deployment_name="test")exceptHttpResponseErroraserror:print("Query failed:{}".format(error.message))LoggingThis library uses the standardlogginglibrary 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 thelogging_enableargument.See full SDK logging documentation with exampleshere.Next stepsView oursamples.Read about the differentfeaturesof the Question Answering service.Try our servicedemos.ContributingSee theCONTRIBUTING.mdfor 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, visitcla.microsoft.com.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 theMicrosoft Open Source Code of Conduct. For more information see theCode of Conduct FAQor contactopencode@microsoft.comwith any additional questions or comments.