Azure.AI.Language.QuestionAnswering
1.1.0
Prefix Reserved
dotnet add package Azure.AI.Language.QuestionAnswering --version 1.1.0
NuGet\Install-Package Azure.AI.Language.QuestionAnswering -Version 1.1.0
<PackageReference Include="Azure.AI.Language.QuestionAnswering" Version="1.1.0" />
paket add Azure.AI.Language.QuestionAnswering --version 1.1.0
#r "nuget: Azure.AI.Language.QuestionAnswering, 1.1.0"
// Install Azure.AI.Language.QuestionAnswering as a Cake Addin #addin nuget:?package=Azure.AI.Language.QuestionAnswering&version=1.1.0 // Install Azure.AI.Language.QuestionAnswering as a Cake Tool #tool nuget:?package=Azure.AI.Language.QuestionAnswering&version=1.1.0
Azure Cognitive Language Services Question Answering client library for .NET
The Question Answering service 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 user behavior.
Source code | Package (NuGet) | API reference documentation | Product documentation | Samples | Migration guide
Getting started
Install the package
Install the Azure Cognitive Language Services Question Answering client library for .NET with NuGet:
dotnet add package Azure.AI.Language.QuestionAnswering
Prerequisites
- An Azure subscription
- An existing Question Answering resource
Though you can use this SDK to create and import conversation projects, Language Studio is the preferred method for creating projects.
Authenticate the client
In order to interact with the Question Answering service, you'll need to either create an instance of the QuestionAnsweringClient
class for querying existing projects or an instance of the QuestionAnsweringAuthoringClient
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.
Get an API key
You can get the endpoint and an API key from the Cognitive Services resource or Question Answering resource in the Azure Portal.
Alternatively, use the Azure CLI command shown below to get the API key from the Question Answering resource.
az cognitiveservices account keys list --resource-group <resource-group-name> --name <resource-name>
Create a QuestionAnsweringClient
To use the QuestionAnsweringClient
, make sure you use the right namespaces:
using Azure.Core;
using Azure.AI.Language.QuestionAnswering;
With your endpoint and API key you can instantiate a QuestionAnsweringClient
:
Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com/");
AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);
Create a QuestionAnsweringAuthoringClient
To use the QuestionAnsweringAuthoringClient
, use the following namespace in addition to those above, if needed.
using Azure.AI.Language.QuestionAnswering.Authoring;
With your endpoint and API key, you can instantiate a QuestionAnsweringAuthoringClient
:
Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com/");
AzureKeyCredential credential = new AzureKeyCredential("{api-key}");
QuestionAnsweringAuthoringClient client = new QuestionAnsweringAuthoringClient(endpoint, credential);
Create a client using Azure Active Directory authentication
You can also create a QuestionAnsweringClient
or QuestionAnsweringAuthoringClient
using Azure Active Directory (AAD) authentication. Your user or service principal must be assigned the "Cognitive Services Language Reader" role.
Using the DefaultAzureCredential you can authenticate a service using Managed Identity or a service principal, authenticate as a developer working on an application, and more all without changing code.
Before you can use the DefaultAzureCredential
, or any credential type from Azure.Identity, you'll first need to install the Azure.Identity package.
To use DefaultAzureCredential
with a client ID and secret, you'll need to set the AZURE_TENANT_ID
, AZURE_CLIENT_ID
, and AZURE_CLIENT_SECRET
environment variables; alternatively, you can pass those values
to the ClientSecretCredential
also in Azure.Identity.
Make sure you use the right namespace for DefaultAzureCredential
at the top of your source file:
using Azure.Identity;
Then you can create an instance of DefaultAzureCredential
and pass it to a new instance of your client:
Uri endpoint = new Uri("https://myaccount.cognitiveservices.azure.com");
DefaultAzureCredential credential = new DefaultAzureCredential();
QuestionAnsweringClient client = new QuestionAnsweringClient(endpoint, credential);
Note that regional endpoints do not support AAD authentication. Instead, create a custom domain name for your resource to use AAD authentication.
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. It provides both synchronous and asynchronous APIs to ask questions.
QuestionAnsweringAuthoringClient
The QuestionAnsweringAuthoringClient
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.
Thread safety
We guarantee that all client instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing client instances is always safe, even across threads.
Additional concepts
Client options | Accessing the response | Long-running operations | Handling failures | Diagnostics | Mocking | Client lifetime
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.
Ask a question
The only input required to a ask a question using an existing knowledge base is just the question itself:
string projectName = "{ProjectName}";
string deploymentName = "{DeploymentName}";
QuestionAnsweringProject project = new QuestionAnsweringProject(projectName, deploymentName);
Response<AnswersResult> response = client.GetAnswers("How long should my Surface battery last?", project);
foreach (KnowledgeBaseAnswer answer in response.Value.Answers)
{
Console.WriteLine($"({answer.Confidence:P2}) {answer.Answer}");
Console.WriteLine($"Source: {answer.Source}");
Console.WriteLine();
}
You can set additional properties on QuestionAnsweringClientOptions
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, you can ask a follow-up question provided the previous question-answering ID and, optionally, the exact question the user asked:
string projectName = "{ProjectName}";
string deploymentName = "{DeploymentName}";
// Answers are ordered by their ConfidenceScore so assume the user choose the first answer below:
KnowledgeBaseAnswer previousAnswer = answers.Answers.First();
QuestionAnsweringProject project = new QuestionAnsweringProject(projectName, deploymentName);
AnswersOptions options = new AnswersOptions
{
AnswerContext = new KnowledgeBaseAnswerContext(previousAnswer.QnaId.Value)
};
Response<AnswersResult> response = client.GetAnswers("How long should charging take?", project, options);
foreach (KnowledgeBaseAnswer answer in response.Value.Answers)
{
Console.WriteLine($"({answer.Confidence:P2}) {answer.Answer}");
Console.WriteLine($"Source: {answer.Source}");
Console.WriteLine();
}
QuestionAnsweringAuthoringClient
The following examples show common scenarios using the QuestionAnsweringAuthoringClient
instance created in this section.
Create a new project
To create a new project, you must specify the project's name and a create a RequestContent
instance with the parameters needed to set up the project.
// Set project name and request content parameters
string newProjectName = "{ProjectName}";
RequestContent creationRequestContent = RequestContent.Create(
new {
description = "This is the description for a test project",
language = "en",
multilingualResource = false,
settings = new {
defaultAnswer = "No answer found for your question."
}
}
);
Response creationResponse = client.CreateProject(newProjectName, creationRequestContent);
// Projects can be retrieved as follows
Pageable<BinaryData> projects = client.GetProjects();
Console.WriteLine("Projects: ");
foreach (BinaryData project in projects)
{
Console.WriteLine(project);
}
Deploy your project
Your projects can be deployed using the DeployProjectAsync
or the synchronous DeployProject
. All you need to specify is the project's name and the deployment name that you wish to use. Please note that the service will not allow you to deploy empty projects.
// Set deployment name and start operation
string newDeploymentName = "{DeploymentName}";
Operation<BinaryData> deploymentOperation = client.DeployProject(WaitUntil.Completed, newProjectName, newDeploymentName);
// Deployments can be retrieved as follows
Pageable<BinaryData> deployments = client.GetDeployments(newProjectName);
Console.WriteLine("Deployments: ");
foreach (BinaryData deployment in deployments)
{
Console.WriteLine(deployment);
}
Add a knowledge source
One way to add content to your project is to add a knowledge source. The following example shows how you can set up a RequestContent
instance to add a new knowledge source of the type "url".
// Set request content parameters for updating our new project's sources
string sourceUri = "{KnowledgeSourceUri}";
RequestContent updateSourcesRequestContent = RequestContent.Create(
new[] {
new {
op = "add",
value = new
{
displayName = "MicrosoftFAQ",
source = sourceUri,
sourceUri = sourceUri,
sourceKind = "url",
contentStructureKind = "unstructured",
refresh = false
}
}
});
Operation<Pageable<BinaryData>> updateSourcesOperation = client.UpdateSources(WaitUntil.Completed, newProjectName, updateSourcesRequestContent);
// Knowledge Sources can be retrieved as follows
Pageable<BinaryData> sources = updateSourcesOperation.Value;
Console.WriteLine("Sources: ");
foreach (BinaryData source in sources)
{
Console.WriteLine(source);
}
Troubleshooting
General
When you interact with the Cognitive Language Services Question Answering client library using the .NET 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-existant knowledge base, a 400
error is returned indicating "Bad Request".
try
{
QuestionAnsweringProject project = new QuestionAnsweringProject("invalid-knowledgebase", "test");
Response<AnswersResult> response = client.GetAnswers("Does this knowledge base exist?", project);
}
catch (RequestFailedException ex)
{
Console.WriteLine(ex.ToString());
}
You will notice that additional information is logged, like the client request ID of the operation.
Azure.RequestFailedException: Please verify azure search service is up, restart the WebApp and try again
Status: 400 (Bad Request)
ErrorCode: BadArgument
Content:
{
"error": {
"code": "BadArgument",
"message": "Please verify azure search service is up, restart the WebApp and try again"
}
}
Headers:
x-envoy-upstream-service-time: 23
apim-request-id: 76a83876-22d1-4977-a0b1-559a674f3605
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options: nosniff
Date: Wed, 30 Jun 2021 00:32:07 GMT
Content-Length: 139
Content-Type: application/json; charset=utf-8
Setting up console logging
The simplest way to see the logs is to enable console logging. To create an Azure SDK log listener that outputs messages to the console use the AzureEventSourceListener.CreateConsoleLogger
method.
// Setup a listener to monitor logged events.
using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();
To learn more about other logging mechanisms see here.
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.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Azure.Core (>= 1.25.0)
- System.Text.Json (>= 4.7.2)
NuGet packages (3)
Showing the top 3 NuGet packages that depend on Azure.AI.Language.QuestionAnswering:
Package | Downloads |
---|---|
Encamina.Enmarcha.AI.QuestionsAnswering.Azure
Package Description |
|
Zaria.AI
This framework provides a simple, attribute-driven, low-code API for building text based interactive dialog. It can be used to build AI BOTs, CLIs and command line tools, workflow orchestrators, and other general command processing utilities! Find out more about Zaria.AI here: https://github.com/thinkmine/zaria.ai |
|
Kopylowi.Utility.Cognitive
Package Description |
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
1.1.0 | 195,465 | 10/14/2022 |
1.1.0-beta.2 | 33,351 | 7/19/2022 |
1.1.0-beta.1 | 4,168 | 2/8/2022 |
1.0.0 | 45,468 | 11/3/2021 |
1.0.0-beta.2 | 506 | 10/5/2021 |
1.0.0-beta.1 | 330 | 7/27/2021 |