Microsoft Corporation Azure Ai Language Questionanswering Client Library for Python
Project description
Azure AI Language Question Answering client library for Python
Question Answering is an Azure AI Language capability that lets you build a conversational, question‑and‑answer layer over your existing data. It extracts question/answer pairs from semi‑structured content (FAQ pages, manuals, documents) and uses them to answer user questions with the most relevant answer automatically.
Source code | Package (PyPI) | Package (Conda) | API reference | Product documentation | Samples | Question Answering REST API
Python 2.7 is not supported. For details see the Azure SDK for Python end-of-support notice.
Getting started
Prerequisites
- Python 3.9 or later.
- An Azure subscription.
- An Azure Language resource (with a custom domain endpoint if you plan to use Azure Active Directory authentication).
Install the package
Install the Azure Question Answering client library for Python with pip:
python -m pip install azure-ai-language-questionanswering
This version of the client library targets the service REST API version
2025-05-15-preview.
Authenticate the client
In order to interact with the Question Answering service, you'll create an instance of the QuestionAnsweringClient (or the AuthoringClient in the separate authoring package). The recommended approach is to use Azure Active Directory via DefaultAzureCredential from the azure-identity library. This avoids embedding keys, enables managed identity in production, and unifies authentication across Azure SDKs.
Important: To use Azure AD (AAD) you must use your resource's custom subdomain endpoint (for example:
https://<my-subdomain>.cognitiveservices.azure.com/); legacy regional generic endpoints (e.g.,https://eastus.api.cognitive.microsoft.com) do not support AAD token authentication.
Recommended: DefaultAzureCredential
Prerequisites for AAD authentication:
- Install azure-identity
- Register an AAD application
- Grant access to the Language resource (e.g., assign the "Cognitive Services Language Reader" role, plus writer roles if needed for authoring)
Set these environment variables only if you’re using a service principal with a client secret (otherwise, if you rely on Azure CLI / VS Code login or Managed Identity, you can skip this step): AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
Then create the client:
from azure.identity import DefaultAzureCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
endpoint = "https://<my-subdomain>.cognitiveservices.azure.com/" # custom subdomain endpoint
credential = DefaultAzureCredential()
client = QuestionAnsweringClient(endpoint, credential)
Authoring (if using the separate authoring package):
from azure.identity import DefaultAzureCredential
from azure.ai.language.questionanswering.authoring import AuthoringClient
endpoint = "https://<my-subdomain>.cognitiveservices.azure.com/"
credential = DefaultAzureCredential()
authoring_client = AuthoringClient(endpoint, credential)
Alternative: API key credential
For quick starts or scripts where you have not yet configured AAD, you can use an API key with AzureKeyCredential. You can obtain the key from the Azure Portal, or via the CLI:
az cognitiveservices account keys list --resource-group <resource-group-name> --name <resource-name>
Then:
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
endpoint = "https://<my-account>.cognitiveservices.azure.com" # regional or custom subdomain
credential = AzureKeyCredential("<api-key>")
client = QuestionAnsweringClient(endpoint, credential)
Note: You can seamlessly switch between key and AAD auth — no code changes beyond the credential object.
Why DefaultAzureCredential?
- Eliminates hard‑coded secrets
- Works locally (developer tools), in CI (service principal / federated), and in production (Managed Identity)
- Centralizes token acquisition & caching
- Supports future auth enhancements without code changes
Key concepts
QuestionAnsweringClient
The QuestionAnsweringClient 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.
Authoring (project creation, knowledge source management, deployment) has moved to a separate package and is intentionally not covered in this runtime client README.
Examples
QuestionAnsweringClient usage examples
The azure-ai-language-questionanswering client library provides both synchronous and asynchronous APIs.
Ask a question (options object)
The only input required to ask a question using a knowledge base is just the question itself:
import os
from azure.identity import DefaultAzureCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
from azure.ai.language.questionanswering.models import AnswersOptions
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"] # must be a custom subdomain for AAD
client = QuestionAnsweringClient(endpoint, DefaultAzureCredential())
options = AnswersOptions(
question="How long should my Surface battery last?",
# Optional extra parameters:
# confidence_threshold=0.2,
# top=5,
# short_answer_options=qna.ShortAnswerOptions(top=1)
)
response = client.get_answers(options, project_name="FAQ", deployment_name="production")
for answer in response.answers:
print(f"({answer.confidence:.2f}) {answer.answer}")
print(f"Source: {answer.source}")
You can also pass optional parameters like confidence_threshold, top, or short_answer_options inside the AnswersOptions object.
Ask a question (flattened)
For convenience, you can also call get_answers directly with keyword parameters:
# Equivalent flattened form - same result as above
response = client.get_answers(
question="How long should my Surface battery last?",
project_name="FAQ",
deployment_name="production",
# Optional parameters can be passed directly:
# confidence_threshold=0.2,
# top=5
)
for answer in response.answers:
print(f"({answer.confidence:.2f}) {answer.answer}")
print(f"Source: {answer.source}")
Follow-up question (options object)
If your knowledge base is configured for chit-chat, the answers from the knowledge base may include suggested prompts for follow-up questions to 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:
from azure.ai.language.questionanswering.models import AnswersOptions, KnowledgeBaseAnswerContext
follow_up_options = AnswersOptions(
question="How long should charging take?",
answer_context=KnowledgeBaseAnswerContext(previous_qna_id=previous_answer.qna_id),
)
follow_up = client.get_answers(follow_up_options, project_name="FAQ", deployment_name="production")
for answer in follow_up.answers:
print(f"({answer.confidence:.2f}) {answer.answer}")
Follow-up question (flattened)
import os
from azure.identity import DefaultAzureCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
from azure.ai.language.questionanswering.models import KnowledgeBaseAnswerContext
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
client = QuestionAnsweringClient(endpoint, DefaultAzureCredential())
output = client.get_answers(
question="How long should charging take?",
answer_context=KnowledgeBaseAnswerContext(previous_qna_id=previous_answer.qna_id),
project_name="FAQ",
deployment_name="production"
)
for candidate in output.answers:
print(f"({candidate.confidence}) {candidate.answer}")
print(f"Source: {candidate.source}")
Async usage (options object)
The above examples can also be run asynchronously using the clients in the aio namespace:
import os
import asyncio
from azure.identity import DefaultAzureCredential
from azure.ai.language.questionanswering.aio import QuestionAnsweringClient
from azure.ai.language.questionanswering.models import AnswersOptions
async def main():
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
client = QuestionAnsweringClient(endpoint, DefaultAzureCredential())
options = AnswersOptions(question="How long should my Surface battery last?")
response = await client.get_answers(options, project_name="FAQ", deployment_name="production")
for answer in response.answers:
print(f"({answer.confidence:.2f}) {answer.answer}")
asyncio.run(main())
Async usage (flattened)
import os
import asyncio
from azure.identity import DefaultAzureCredential
from azure.ai.language.questionanswering.aio import QuestionAnsweringClient
async def main():
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
client = QuestionAnsweringClient(endpoint, DefaultAzureCredential())
output = await client.get_answers(
question="How long should my Surface battery last?",
project_name="FAQ",
deployment_name="production"
)
for candidate in output.answers:
print(f"({candidate.confidence:.2f}) {candidate.answer}")
asyncio.run(main())
Filtering with metadata (QueryFilters)
You can narrow answers using metadata stored in your knowledge base:
from azure.ai.language.questionanswering.models import (
AnswersOptions,
QueryFilters,
MetadataFilter,
MetadataRecord
)
# Tuple form (supported)
metadata_filter_tuple = MetadataFilter(metadata=[("product", "surface"), ("locale", "en-US")])
# MetadataRecord form (recommended for static typing)
metadata_filter_records = MetadataFilter(metadata=[
MetadataRecord(key="product", value="surface"),
MetadataRecord(key="locale", value="en-US")
])
options = AnswersOptions(
question="How long should my Surface battery last?",
filters=QueryFilters(metadata_filter=metadata_filter_tuple),
confidence_threshold=0.2,
top=3
)
resp = client.get_answers(options, project_name="FAQ", deployment_name="production")
for ans in resp.answers:
print(f"{ans.answer} ({ans.confidence:.2f})")
# Note: Passing metadata as a dict (e.g. {'product': 'surface'}) is no longer supported.
Optional Configuration
Optional keyword arguments can be passed in at the client and per-operation level. The azure-core reference documentation describes available configurations for retries, logging, transport protocols, and more.
Troubleshooting
General
Azure Question Answering clients raise exceptions defined in Azure 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 for REST API requests.
For example, if you submit a question to a non-existent knowledge base, a 400 error is returned indicating "Bad Request".
from azure.core.exceptions import HttpResponseError
try:
client.get_answers(
question="Why?",
project_name="invalid-knowledge-base",
deployment_name="production"
)
except HttpResponseError as error:
print("Query failed: {}".format(error.message))
Logging
This library uses the standard 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 the full SDK logging documentation with examples in the logging guidance.
API Usage Notes
This library supports both explicit options objects (like AnswersOptions for get_answers and AnswersFromTextOptions for get_answers_from_text) and flattened keyword parameters for convenience. Both approaches are fully supported and equivalent (and work regardless of whether you use DefaultAzureCredential or an API key):
- Options object approach:
client.get_answers(AnswersOptions(question="...", top=5), project_name="...", deployment_name="...") - Flattened parameters:
client.get_answers(question="...", top=5, project_name="...", deployment_name="...")
Choose whichever style best fits your coding preferences - both produce identical results.
Next steps
- View our samples.
- Read about the different features of the Question Answering service.
- Try our service demos.
Contributing
See the CONTRIBUTING.md 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.
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. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Release History
2.0.0b1 (2025-10-27)
Breaking Changes
-
Authoring functionality (project creation, knowledge source management, deployment operations) has been removed from this package and moved to a separate dedicated authoring package / namespace. All references to
AuthoringClient, and related authoring operations have been eliminated from the runtime client distribution. -
Dropped support for Python versions earlier than 3.9 (aligns with Azure SDK Python support policy going forward).
-
Model base class change: all public model types now inherit from
MutableMapping[str, Any](dict-like) instead of the previousModelbase class. As a result they now support standard mutable mapping behavior (key iteration, item assignment, etc.) and any code depending on methods/properties inherited from the old base class should be reviewed/updated. -
Removed client constructor keyword argument
default_language. Per-call language control is now done explicitly via thelanguageproperty onAnswersFromTextOptions(and related options models). The service default remains"en"if a language is not supplied. To change the effective language:- Pass
language="<bcp-47-code>"when constructingAnswersFromTextOptions(e.g."es","zh-Hans"). - Or create / select a project in the desired language in Language Studio when authoring knowledge bases.
The previous implicit fallback (client-level
default_language) has been removed to avoid hidden state and to encourage explicit specification or project-level configuration. - Pass
-
Removed support for passing metadata as
Dict[str,str]toMetadataFilter. Tuple form[("key","value"), ...]andList[MetadataRecord]remain supported.
Features Added
- Documentation improvements: expanded README with authentication guidance, AAD usage, async examples, and troubleshooting section.
Other Changes
- Internal refactoring and dependency grooming in preparation for the authoring/runtime split.
- Changed samples and README examples to use explicit
AnswersOptions/AnswersFromTextOptionsobjects as the first argument when callingget_answersandget_answers_from_text.
1.1.0 (2022-10-13)
Breaking Changes
These changes do not impact the API of stable versions such as 1.0.0. Only code written against a beta version such as 1.1.0b2 may be affected
QuestionAnsweringProjectsClientwas renamed toAuthoringClient.- The
azure.ai.language.questionanswering.projectsnamespace was renamed toazure.ai.language.questionanswering.authoring - Authoring client methods:
begin_deploy_project,begin_import_assets,begin_update_sourcesandbegin_update_qnasnow return a response upon completion of the long-running operation. - Keyword argument
formatrenamed tofile_formatforbegin_exportandbegin_import_assets.
Bugs Fixed
- Fixed a bug where the client-level keyword argument
default_languagewas not being honored forget_answers_from_text.
Other Changes
- Python 3.6 is no longer supported. Please use Python version 3.7 or later. For more details, see Azure SDK for Python version support policy.
- Dropped dependency on
msrest.
1.1.0b2 (2022-07-19)
Features Added
- Added Azure Active Directory (AAD) authentication support
Other Changes
- Python 2.7 is no longer supported. Please use Python version 3.6 or later.
1.1.0b1 (2022-02-08)
Features Added
- Added
QuestionAnsweringProjectsClientfor managing Qna projects. Performing project operations such as create, delete, export, and import project, as well as knowledge sources operations such as adding or listing knowledge sources, Qnas, and synonyms.
1.0.0 (2021-11-03)
- We are now targeting service version
2021-10-01
Breaking Changes
- Method
QuestionAnsweringClient.query_knowledge_basehas been renamed toget_answers - Method
QuestionAnsweringClient.query_texthas been renamed toget_answers_from_text - Model
QueryKnowledgeBaseOptionshas been renamed toAnswersOptions - Method kwarg and model property
QueryKnowledgeBaseOptions.confidence_score_thresholdhas been renamed toAnswersOptions.confidence_threshold - Method kwarg and model property
QueryKnowledgeBaseOptions.answer_span_requesthas been renamed toAnswersOptions.short_answer_options - Method kwarg and model property
QueryKnowledgeBaseOptions.ranker_typehas been renamed toAnswersOptions.ranker_kind - Method kwarg and model property
QueryKnowledgeBaseOptions.contexthas been renamed toAnswersOptions.answer_context - Model
QueryTextOptionshas been renamed toAnswersFromTextOptions - Method kwarg and model property
QueryTextOptions.recordshas been renamed toAnswersFromTextOptions.text_documents - Model
AnswerSpanRequesthas been renamed toShortAnswerOptions - Model property
AnswerSpanRequest.confidence_score_thresholdhas been renamed toShortAnswerOptions.confidence_threshold - Model property
AnswerSpanRequest.top_answers_with_spanhas been renamed toShortAnswerOptions.top - Model
KnowledgeBaseAnswerRequestContexthas been renamed toKnowledgeBaseAnswerContext - Model property
KnowledgeBaseAnswerRequestContext.previous_user_queryhas been renamed toKnowledgeBaseAnswerContext.previous_question - Model
TextRecordhas been renamed toTextDocument - Model
KnowledgeBaseAnswershas been renamed toAnswersResult - Model
TextAnswershas been renamed toAnswersFromTextResult - Model property
KnowledgeBaseAnswer.answer_spanhas been renamed toKnowledgeBaseAnswer.short_answer - Model property
KnowledgeBaseAnswer.idhas been renamed toKnowledgeBaseAnswer.qna_id - Model property
KnowledgeBaseAnswer.confidence_scorehas been renamed toKnowledgeBaseAnswer.confidence - Model property
AnswerSpan.confidence_scorehas been renamed toAnswerSpan.confidence - Model property
TextAnswer.confidence_scorehas been renamed toTextAnswer.confidence - Model property
TextAnswer.answer_spanhas been renamed toTextAnswer.short_answer - Enums
LogicalOperationKindandRankerTypehave been removed - The
operationsandaio.operationsnamespaces are no longer public
Bugs Fixed
- Fixed formating of
MetadataFilter.metadata
1.0.0b2 (2021-10-06)
- We are now targeting service version
2021-07-15-preview
Breaking changes
- The method
QuestionAnsweringClient.query_knowledgebasehas been renamed toquery_knowledge_base. - Options bag model
KnowledgeBaseQueryOptionsforquery_knowledge_baseis renamed toQueryKnowledgeBaseOptions - Options bag model
TextQueryOptionsforquery_textis renamed toQueryTextOptions - The filters model
StrictFiltersis renamed toQueryFilters - Enum
CompoundOperationKindis renamed toLogicalOperationKind - We have removed the
string_index_typeinput to all models and operations. We have also removed theStringIndexTypeenum. - The type of input
metadatatoMetadataFilterhas changed from a dictionary of strings to a list of key-value tuples. For example, the input has changed from{"key": "value"}to[("key", "value")]. - The input to the
query_knowledge_baseandquery_textoverloads that take in a positional model for the body should be considered positional only.
Features Added
- The method
QuestionAnsweringClient.query_textnow supports a list of records as strings, where the ID value will be automatically populated. - Added keyword argument
default_languageontoQuestionAnsweringClient, which has default value'en'. The default language for any operation call will be this default language value.
1.0.0b1 (2021-07-27)
Features Added
- Initial release - supports querying from text records and knowledge bases.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file azure_ai_language_questionanswering-2.0.0b1.tar.gz.
File metadata
- Download URL: azure_ai_language_questionanswering-2.0.0b1.tar.gz
- Upload date:
- Size: 79.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: RestSharp/106.13.0.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e7ea28f63cf2d747130c85006f4ac7e3e53196b45d3b836a09546893ee662c22
|
|
| MD5 |
d98345cc0b8bf38f76593eaa7d2763a8
|
|
| BLAKE2b-256 |
d0a8754210c7f4f9b856d9d80e628175b92e74aa1eab6043147cf2e72d56f162
|
File details
Details for the file azure_ai_language_questionanswering-2.0.0b1-py3-none-any.whl.
File metadata
- Download URL: azure_ai_language_questionanswering-2.0.0b1-py3-none-any.whl
- Upload date:
- Size: 73.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: RestSharp/106.13.0.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
987b7b008ac45289a138b125801f1e347254567dfc4495fdfa68018ddaaa2330
|
|
| MD5 |
699a07d1e1bb0488c7270088daa62139
|
|
| BLAKE2b-256 |
b0eb20b15bfb19981b34aca44c8b8444a49fbfbf15a812b4626332c24cada7f7
|