Skip to content

Commit

Permalink
qna authoring samples (Azure#21881)
Browse files Browse the repository at this point in the history
* generating LLC client

* adding version file

* Update swagger directives

* Python 2 support for now

* update swagger reference

* regenerate client

* add version file

* regen llc client

* regen with authoring

* regen with export fix update

* create and deploy project sample

* export import samples

* some changes

* knowledge source samples

* update "create and deploy" sample

* tmp commit

* update "export import sample"

* update "update knowledge sources sample"

* update samples

* fix "export_import" sample

* minor fix

* update sample for "create and deploy"

* fix list sources

* update "update knowledge sources" sample

* fix synonyms sample

* update main readme

* update samples readme

* remove u" python 2.7 support

* adding async samples

* restructure

* update samples readme

Co-authored-by: antisch <antisch@microsoft.com>
  • Loading branch information
2 people authored and rakshith91 committed Apr 10, 2022
1 parent fc33ffc commit 6974494
Show file tree
Hide file tree
Showing 8 changed files with 815 additions and 5 deletions.
115 changes: 111 additions & 4 deletions sdk/cognitivelanguage/azure-ai-language-questionanswering/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pip install azure-ai-language-questionanswering

### 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. 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].
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 [QuestionAnsweringProjectsClient][questionansweringprojects_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

Expand All @@ -56,15 +56,32 @@ credential = AzureKeyCredential("{api-key}")
client = QuestionAnsweringClient(endpoint, credential)
```

#### Create QuestionAnsweringProjectsClient
With your endpoint and API key, you can instantiate a [QuestionAnsweringProjectsClient][questionansweringprojects_client_class]:

```python
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.projects import QuestionAnsweringProjectsClient

endpoint = "https://{myaccount}.api.cognitive.microsoft.com"
credential = AzureKeyCredential("{api-key}")

client = QuestionAnsweringProjectsClient(endpoint, 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.

### QuestionAnsweringProjectsClient
The [QuestionAnsweringProjectsClient][questionansweringprojects_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.

The following examples show common scenarios using the `client` [created above](#create-questionansweringclient).
Expand All @@ -73,7 +90,7 @@ The following examples show common scenarios using the `client` [created above](
- [Ask a follow-up question](#ask-a-follow-up-question)
- [Asynchronous operations](#asynchronous-operations)

### Ask a question
#### Ask a question

The only input required to ask a question using a knowledge base is just the question itself:

Expand All @@ -91,7 +108,7 @@ for candidate in output.answers:

You can set additional keyword options to limit the number of answers, specify a minimum confidence score, and more.

### Ask a follow-up question
#### 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:

Expand All @@ -112,7 +129,7 @@ for candidate in output.answers:

```

### Asynchronous operations
#### Asynchronous operations

The above examples can also be run asynchronously using the client in the `aio` namespace:

Expand All @@ -129,6 +146,95 @@ output = await client.get_answers(
)
```

### QuestionAnsweringProjectsClient

#### Create a new project

```python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.projects import QuestionAnsweringProjectsClient

# get service secrets
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
key = os.environ["AZURE_QUESTIONANSWERING_KEY"]

# create client
client = QuestionAnsweringProjectsClient(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
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
# 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)
```



## 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.
Expand Down Expand Up @@ -200,6 +306,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct][code_of_con
[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
[questionansweringprojects_client_class]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/azure/ai/language/questionanswering/projects/_question_answering_projects_client.py
[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/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.---
---
page_type: sample
languages:
- python
Expand All @@ -24,6 +24,10 @@ These sample programs show common scenarios for the QuestionAnswering client's o
|[sample_query_knowledgebase.py][query_knowledgebase] and [sample_query_knowledgebase_async.py][query_knowledgebase_async]|Ask a question from a knowledge base|
|[sample_chat.py][chat] and [sample_chat_async.py][chat_async]|Ask a follow-up question (chit-chat)|
|[sample_query_text.py][query_text] and [sample_query_text_async.py][query_text_async]|Ask a question from provided text data|
|[sample_create_and_deploy_project.py][create_and_deploy] and [sample_create_and_deploy_project_async.py][create_and_deploy_async]|sample for creating and deploying a Qna project|
|[sample_export_import_project.py][export_import] and [sample_export_import_project_async.py][export_import_async]|sample for exporting and importing a project|
|[sample_update_knowledge_sources.py][add_knowledge_sources] and [sample_update_knowledge_sources_async.py][add_knowledge_sources_async]|sample for adding knowledge sources|



### Prerequisites
Expand Down Expand Up @@ -55,5 +59,13 @@ pip install --pre azure-ai-language-questionanswering
[chat_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_chat_async.py
[query_text]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/sample_query_text.py
[query_text_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/async_samples/sample_query_text_async.py

[create_and_deploy]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/authoring/sample_create_and_deploy_project.py
[create_and_deploy_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/authoring/async_samples/sample_create_and_deploy_project_async.py
[export_import]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/authoring/sample_export_import_project.py
[export_import_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/authoring/async_samples/sample_export_import_project_async.py
[add_knowledge_sources]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/authoring/sample_update_knowledge_sources.py
[add_knowledge_sources_async]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cognitivelanguage/azure-ai-language-questionanswering/samples/authoring/async_samples/sample_update_knowledge_sources_async.py

[pip]: https://pypi.org/project/pip/
[azure_subscription]: https://azure.microsoft.com/free/
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------

"""
FILE: sample_create_and_deploy_project_async.py
DESCRIPTION:
This sample demonstrates how to create and deploy a Qna project.
USAGE:
python sample_create_and_deploy_project_async.py
Set the environment variables with your own values before running the sample:
1) AZURE_QUESTIONANSWERING_ENDPOINT - the endpoint to your QuestionAnswering resource.
2) AZURE_QUESTIONANSWERING_KEY - your QuestionAnswering API key.
"""

import asyncio

async def sample_create_and_deploy_project_async():
# [START create_and_deploy_project]
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.questionanswering.projects.aio import QuestionAnsweringProjectsClient

# get service secrets
endpoint = os.environ["AZURE_QUESTIONANSWERING_ENDPOINT"]
key = os.environ["AZURE_QUESTIONANSWERING_KEY"]

# create client
client = QuestionAnsweringProjectsClient(endpoint, AzureKeyCredential(key))
async with client:

# create project
project_name = "IssacNewton"
project = await 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"]))

# list projects
print("find created project ..")
qna_projects = client.list_projects()
async for p in qna_projects:
if p["projectName"] == project_name:
print("project: {}".format(p["projectName"]))
print("\tlanguage: {}".format(p["language"]))
print("\tdescription: {}".format(p["description"]))

# update sources (REQUIRED TO DEPLOY PROJECT)
update_sources_poller = await 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"
}
}
]
)
await update_sources_poller.result()

# list sources
print("list project sources")
sources = client.list_sources(
project_name=project_name
)
async 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 project
deployment_poller = await client.begin_deploy_project(
project_name=project_name,
deployment_name="production"
)
await deployment_poller.result()

# list all deployments
deployments = client.list_deployments(
project_name=project_name
)

print("view project deployments")
async for d in deployments:
print(d)

# [END create_and_deploy_project]

if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(sample_create_and_deploy_project_async())
Loading

0 comments on commit 6974494

Please sign in to comment.