Quickstart: Get answers to a question from a knowledge base with C#

This quickstart walks you through programmatically getting an answer from a published QnA Maker knowledge base. The knowledge base contains questions and answers from data sources such as FAQs. The question is sent to the QnA Maker service. The response includes the top-predicted answer.

Prerequisites

  • Latest Visual Studio Community edition.

  • You must have a QnA Maker service. To retrieve your key, select Keys under Resource Management in your Azure dashboard for your QnA Maker resource.

  • Publish page settings. If you do not have a published knowledge base, create an empty knowledge base, then import a knowledge base on the Settings page, then publish. You can download and use this basic knowledge base.

    The publish page settings include POST route value, Host value, and EndpointKey value.

    Publish settings

The code for this quickstart is in the https://github.com/Azure-Samples/cognitive-services-qnamaker-csharp repository.

Create a knowledge base project

  1. Open Visual Studio 2019 Community edition.
  2. Create a new Console App (.NET Core) project and name the project QnaMakerQuickstart. Accept the defaults for the remaining settings.

Add the required dependencies

At the top of the Program.cs file, replace the single using statement with the following lines to add necessary dependencies to the project:

using System;
using System.Net.Http;
using System.Text;

Add the required constants

At the top of the Program class, inside the Main, add the required constants to access QnA Maker. These values are on the Publish page after you publish the knowledge base.

private const string endpointVar = "QNA_MAKER_RESOURCE_ENDPOINT";
private const string endpointKeyVar = "QNA_MAKER_ENDPOINT_KEY";
private const string kbIdVar = "QNA_MAKER_KB_ID";

// Your QnA Maker resource endpoint.
// From Publish Page: HOST
// Example: https://YOUR-RESOURCE-NAME.azurewebsites.net/
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpointVar);
// Authorization endpoint key
// From Publish Page
// Note this is not the same as your QnA Maker subscription key.
private static readonly string endpointKey = Environment.GetEnvironmentVariable(endpointKeyVar);
private static readonly string kbId = Environment.GetEnvironmentVariable(kbIdVar);

/// <summary>
/// Static constuctor. Verifies that we found the subscription key and
/// endpoint in the environment variables.
/// </summary>
static Program()
{
    if (null == endpointKey)
    {
        throw new Exception("Please set/export the environment variable: " + endpointKeyVar);
    }
    if (null == endpoint)
    {
        throw new Exception("Please set/export the environment variable: " + endpointVar);
    }
    if (null == kbId)
    {
        throw new Exception("Please set/export the environment variable: " + kbIdVar);
    }
}

Add a POST request to send question and get answer

The following code makes an HTTPS request to the QnA Maker API to send the question to the knowledge base and receives the response:

static void Main(string[] args)
{
    var uri = endpoint + "/qnamaker/v4.0/knowledgebases/" + kbId + "/generateAnswer";

    // JSON format for passing question to service
    string question = @"{'question': 'Is the QnA Maker Service free?','top': 3}";

    // Create http client
    using (var client = new HttpClient())
    using (var request = new HttpRequestMessage())
    {
        // POST method
        request.Method = HttpMethod.Post;

        // Add host + service to get full URI
        request.RequestUri = new Uri(uri);

        // set question
        request.Content = new StringContent(question, Encoding.UTF8, "application/json");

        // set authorization
        request.Headers.Add("Authorization", "EndpointKey " + endpointKey);

        // Send request to Azure service, get response
        var response = client.SendAsync(request).Result;
        var jsonResponse = response.Content.ReadAsStringAsync().Result;

        // Output JSON response
        Console.WriteLine(jsonResponse);

        Console.WriteLine("Press any key to continue.");
        Console.ReadKey();
    }
}

The Authorization header's value includes the string EndpointKey.

Learn more about the request and response.

Build and run the program

Build and run the program from Visual Studio. It will automatically send the request to the QnA Maker API, then it will print to the console window.

Request and response JSON

An example JSON-formatted question for the REST API:

{
    "question": "Is the QnA Maker Service free?",
    "top": 3
}

The question includes a property to return the top three answers.

The answer is returned in a JSON object:

{
  "answers": [
    {
      "questions": [
        "How do I embed the QnA Maker service in my website?"
      ],
      "answer": "Follow these steps to embed the QnA Maker service as a web-chat control in your website:\n\n\n1.  Create your FAQ bot by following the instructions [here](https://docs.microsoft.com/azure/cognitive-services/qnamaker/tutorials/create-qna-bot).\n2.  Enable the web chat by following the steps [here](https://docs.microsoft.com/azure/bot-service/bot-service-channel-connect-webchat)",
      "score": 70.95,
      "id": 16,
      "source": "https://docs.microsoft.com/azure/cognitive-services/qnamaker/faqs",
      "metadata": []
    },
    {
      "questions": [
        "Do I need to use Bot Framework in order to use QnA Maker?"
      ],
      "answer": "No, you do not need to use the Bot Framework with QnA Maker. However, QnA Maker is offered as one of several templates in Azure Bot Service. Bot Service enables rapid intelligent bot development through Microsoft Bot Framework, and it runs in a server-less environment.",
      "score": 46.94,
      "id": 14,
      "source": "https://docs.microsoft.com/azure/cognitive-services/qnamaker/faqs",
      "metadata": []
    },
    {
      "questions": [
        "How can I create a bot with QnA Maker?"
      ],
      "answer": "Follow the instructions in [this](https://docs.microsoft.com/azure/cognitive-services/qnamaker/tutorials/create-qna-bot)documentation to create your Bot with Azure Bot Service.",
      "score": 43.25,
      "id": 15,
      "source": "https://docs.microsoft.com/azure/cognitive-services/qnamaker/faqs",
      "metadata": []
    }
  ]
}

Clean up resources

When you are done with the quickstart, remove all the files created in this quickstart. Sign on to QnA Maker, and delete the KB.

Next steps