File size: 18,380 Bytes
065fee7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 |
# Azure Cognitive Language Service 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]
| [Package (Conda)](https://anaconda.org/microsoft/azure-ai-language-questionanswering/)
| [API reference documentation][questionanswering_refdocs]
| [Product documentation][questionanswering_docs]
| [Samples][questionanswering_samples]
| [Analysis REST API documentation][questionanswering_rest_docs]
| [Authoring REST API documentation][questionanswering_rest_docs_authoring]
## _Disclaimer_
_Azure SDK Python packages support for Python 2.7 ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691_
## Getting started
### Prerequisites
- Python 3.7 or later is required to use this package.
- An [Azure subscription][azure_subscription]
- A [Language Service][language_service] resource
### Install the package
Install the Azure Question Answering client library for Python with [pip][pip_link]:
```bash
pip install azure-ai-language-questionanswering
```
> Note: this version of the client library defaults to the service API version `2021-10-01`.
### 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 or an instance of the [AuthoringClient][authoring_client_class] for managing projects within your resource. You will need an **endpoint**, and an **API key** to 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 Language resource in the [Azure Portal][azure_portal].
Alternatively, use the [Azure CLI][azure_cli] command shown below to get the API key from the Language resource.
```powershell
az cognitiveservices account keys list --resource-group <resource-group-name> --name <resource-name>
```
#### Create QuestionAnsweringClient
Once you've determined your **endpoint** and **API key** you can instantiate a [QuestionAnsweringClient][questionanswering_client_class]:
```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)
```
#### Create AuthoringClient
With your endpoint and API key, you can instantiate a [AuthoringClient][authoring_client_class]:
```python
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.authoring import AuthoringClient
endpoint = "https://{myaccount}.api.cognitive.microsoft.com"
credential = AzureKeyCredential("{api-key}")
client = AuthoringClient(endpoint, credential)
```
#### Create a client with an Azure Active Directory Credential
To use an [Azure Active Directory (AAD) token credential][cognitive_authentication_aad],
provide an instance of the desired credential type obtained from the
[azure-identity][azure_identity_credentials] library.
Note that regional endpoints do not support AAD authentication. Create a [custom subdomain][custom_subdomain]
name for your resource in order to use this type of authentication.
Authentication with AAD requires some initial setup:
- [Install azure-identity][install_azure_identity]
- [Register a new AAD application][register_aad_app]
- [Grant access][grant_role_access] to the Language service by assigning the "Cognitive Services Language Reader" role to your service principal.
After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use.
As an example, [DefaultAzureCredential][default_azure_credential]
can 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_SECRET`
Use the returned token credential to authenticate the client:
```python
from azure.ai.language.questionanswering import QuestionAnsweringClient
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
client = QuestionAnsweringClient(endpoint="https://<my-custom-subdomain>.cognitiveservices.azure.com/", credential=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.
### AuthoringClient
The [AuthoringClient][authoring_client_class] provides 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.
## Examples
### QuestionAnsweringClient
The `azure-ai-language-questionanswering` client library provides both synchronous and asynchronous APIs.
- [Ask a question](#ask-a-question "Ask a question")
- [Ask a follow-up question](#ask-a-follow-up-question "Ask a follow-up question")
- [Create a new project](#create-a-new-project "Create a new project")
- [Add a knowledge source](#add-a-knowledge-source "Add a knowledge source")
- [Deploy your project](#deploy-your-project "Deploy your project")
- [Asynchronous operations](#asynchronous-operations "Asynchronous operations")
#### Ask a question
The only input required to ask a question using a knowledge base is just the question itself:
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
endpoint = 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="production"
)
for candidate in output.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 question
If your knowledge base is configured for [chit-chat][questionanswering_docs_chat], the answers from the knowledge base may include suggested [prompts for follow-up questions][questionanswering_refdocs_prompts] 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:
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering import QuestionAnsweringClient
from azure.ai.language.questionanswering import models
endpoint = 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="production"
)
for candidate in output.answers:
print("({}) {}".format(candidate.confidence, candidate.answer))
print("Source: {}".format(candidate.source))
```
#### Create a new project
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.authoring import AuthoringClient
# get service secrets
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
key = os.environ["AZURE_QUESTIONANSWERING_KEY"]
# create client
client = AuthoringClient(endpoint, AzureKeyCredential(key))
with client:
# create project
project_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 source
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.authoring import AuthoringClient
# get service secrets
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
key = os.environ["AZURE_QUESTIONANSWERING_KEY"]
# create client
client = 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 sources
print("list project sources")
sources = client.list_sources(
project_name=project_name
)
for source in sources:
print("project: {}".format(source["displayName"]))
print("\tsource: {}".format(source["source"]))
print("\tsource Uri: {}".format(source["sourceUri"]))
print("\tsource kind: {}".format(source["sourceKind"]))
```
#### Deploy your project
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.authoring import AuthoringClient
# get service secrets
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
key = os.environ["AZURE_QUESTIONANSWERING_KEY"]
# create client
client = AuthoringClient(endpoint, AzureKeyCredential(key))
project_name = "IssacNewton"
# deploy project
deployment_poller = client.begin_deploy_project(
project_name=project_name,
deployment_name="production"
)
deployment_poller.result()
# list all deployments
deployments = client.list_deployments(
project_name=project_name
)
print("view project deployments")
for d in deployments:
print(d)
```
#### Asynchronous operations
The above examples can also be run asynchronously using the clients in the `aio` namespace:
```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.aio import QuestionAnsweringClient
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
key = os.environ["AZURE_QUESTIONANSWERING_KEY"]
client = QuestionAnsweringClient(endpoint, AzureKeyCredential(key))
output = await client.get_answers(
question="How long should my Surface battery last?",
project_name="FAQ",
deployment_name="production"
)
```
## 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 Question Answering clients raise exceptions defined in [Azure Core][azure_core_readme].
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][questionanswering_rest_docs] requests.
For example, if you submit a question to a non-existent knowledge base, a `400` error is returned indicating "Bad Request".
```python
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][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.
<!-- LINKS -->
[azure_cli]: https://docs.microsoft.com/cli/azure/
[azure_portal]: https://portal.azure.com/
[azure_subscription]: https://azure.microsoft.com/free/
[language_service]: https://ms.portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics
[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://azuresdkdocs.blob.core.windows.net/$web/python/azure-ai-language-questionanswering/latest/azure.ai.language.questionanswering.html#azure.ai.language.questionanswering.QuestionAnsweringClient
[authoring_client_class]: https://aka.ms/azsdk/python/questionansweringauthoringclient
[questionanswering_refdocs_prompts]: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-ai-language-questionanswering/latest/azure.ai.language.questionanswering.models.html#azure.ai.language.questionanswering.models.KnowledgeBaseAnswerDialog
[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://pypi.org/project/azure-ai-language-questionanswering/
[questionanswering_refdocs]: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-ai-language-questionanswering/latest/azure.ai.language.questionanswering.html
[questionanswering_samples]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/README.md
[cognitive_authentication_aad]: https://docs.microsoft.com/azure/cognitive-services/authentication#authenticate-with-azure-active-directory
[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials
[custom_subdomain]: https://docs.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain
[install_azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#install-the-package
[register_aad_app]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal
[grant_role_access]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal
[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential
[questionanswering_rest_docs]: https://learn.microsoft.com/rest/api/language/question-answering?view=rest-language-2021-10-01
[questionanswering_rest_docs_authoring]: https://learn.microsoft.com/rest/api/language/question-answering-projects?view=rest-language-2021-10-01
![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Ftemplate%2Fazure-template%2FREADME.png)
|