Skip to main content

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

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:

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 previous Model base 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 the language property on AnswersFromTextOptions (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 constructing AnswersFromTextOptions (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.

  • Removed support for passing metadata as Dict[str,str] to MetadataFilter. Tuple form [("key","value"), ...] and List[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 / AnswersFromTextOptions objects as the first argument when calling get_answers and get_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

  • QuestionAnsweringProjectsClient was renamed to AuthoringClient.
  • The azure.ai.language.questionanswering.projects namespace was renamed to azure.ai.language.questionanswering.authoring
  • Authoring client methods: begin_deploy_project, begin_import_assets, begin_update_sources and begin_update_qnas now return a response upon completion of the long-running operation.
  • Keyword argument format renamed to file_format for begin_export and begin_import_assets.

Bugs Fixed

  • Fixed a bug where the client-level keyword argument default_language was not being honored for get_answers_from_text.

Other Changes

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 QuestionAnsweringProjectsClient for 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_base has been renamed to get_answers
  • Method QuestionAnsweringClient.query_text has been renamed to get_answers_from_text
  • Model QueryKnowledgeBaseOptions has been renamed to AnswersOptions
  • Method kwarg and model property QueryKnowledgeBaseOptions.confidence_score_threshold has been renamed to AnswersOptions.confidence_threshold
  • Method kwarg and model property QueryKnowledgeBaseOptions.answer_span_request has been renamed to AnswersOptions.short_answer_options
  • Method kwarg and model property QueryKnowledgeBaseOptions.ranker_type has been renamed to AnswersOptions.ranker_kind
  • Method kwarg and model property QueryKnowledgeBaseOptions.context has been renamed to AnswersOptions.answer_context
  • Model QueryTextOptions has been renamed to AnswersFromTextOptions
  • Method kwarg and model property QueryTextOptions.records has been renamed to AnswersFromTextOptions.text_documents
  • Model AnswerSpanRequest has been renamed to ShortAnswerOptions
  • Model property AnswerSpanRequest.confidence_score_threshold has been renamed to ShortAnswerOptions.confidence_threshold
  • Model property AnswerSpanRequest.top_answers_with_span has been renamed to ShortAnswerOptions.top
  • Model KnowledgeBaseAnswerRequestContext has been renamed to KnowledgeBaseAnswerContext
  • Model property KnowledgeBaseAnswerRequestContext.previous_user_query has been renamed to KnowledgeBaseAnswerContext.previous_question
  • Model TextRecord has been renamed to TextDocument
  • Model KnowledgeBaseAnswers has been renamed to AnswersResult
  • Model TextAnswers has been renamed to AnswersFromTextResult
  • Model property KnowledgeBaseAnswer.answer_span has been renamed to KnowledgeBaseAnswer.short_answer
  • Model property KnowledgeBaseAnswer.id has been renamed to KnowledgeBaseAnswer.qna_id
  • Model property KnowledgeBaseAnswer.confidence_score has been renamed to KnowledgeBaseAnswer.confidence
  • Model property AnswerSpan.confidence_score has been renamed to AnswerSpan.confidence
  • Model property TextAnswer.confidence_score has been renamed to TextAnswer.confidence
  • Model property TextAnswer.answer_span has been renamed to TextAnswer.short_answer
  • Enums LogicalOperationKind and RankerType have been removed
  • The operations and aio.operations namespaces 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_knowledgebase has been renamed to query_knowledge_base.
  • Options bag model KnowledgeBaseQueryOptions for query_knowledge_base is renamed to QueryKnowledgeBaseOptions
  • Options bag model TextQueryOptions for query_text is renamed to QueryTextOptions
  • The filters model StrictFilters is renamed to QueryFilters
  • Enum CompoundOperationKind is renamed to LogicalOperationKind
  • We have removed the string_index_type input to all models and operations. We have also removed the StringIndexType enum.
  • The type of input metadata to MetadataFilter has 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_base and query_text overloads that take in a positional model for the body should be considered positional only.

Features Added

  • The method QuestionAnsweringClient.query_text now supports a list of records as strings, where the ID value will be automatically populated.
  • Added keyword argument default_language onto QuestionAnsweringClient, 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure_ai_language_questionanswering-2.0.0b1.tar.gz (79.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file azure_ai_language_questionanswering-2.0.0b1.tar.gz.

File metadata

File hashes

Hashes for azure_ai_language_questionanswering-2.0.0b1.tar.gz
Algorithm Hash digest
SHA256 e7ea28f63cf2d747130c85006f4ac7e3e53196b45d3b836a09546893ee662c22
MD5 d98345cc0b8bf38f76593eaa7d2763a8
BLAKE2b-256 d0a8754210c7f4f9b856d9d80e628175b92e74aa1eab6043147cf2e72d56f162

See more details on using hashes here.

File details

Details for the file azure_ai_language_questionanswering-2.0.0b1-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_ai_language_questionanswering-2.0.0b1-py3-none-any.whl
Algorithm Hash digest
SHA256 987b7b008ac45289a138b125801f1e347254567dfc4495fdfa68018ddaaa2330
MD5 699a07d1e1bb0488c7270088daa62139
BLAKE2b-256 b0eb20b15bfb19981b34aca44c8b8444a49fbfbf15a812b4626332c24cada7f7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page