Skip to main content

Microsoft Azure Conversational Language Understanding Client Library for Python

Project description

Build Status

Azure Conversational Language Understanding client library for Python

Conversational Language Understanding, aka CLU for short, is a cloud-based conversational AI service which is mainly used in bots to extract useful information from user utterance (natural language processing). The CLU analyze api encompasses two projects; conversation, and orchestration projects. You can use the "conversation" project if you want to extract intents (intention behind a user utterance) and custom entities. You can also use the "orchestration" project which orchestrates multiple language apps to get the best response (language apps like Question Answering, Luis, and Conversation).

Source code | Package (PyPI) | API reference documentation | Product documentation | Samples

Disclaimer

Azure SDK Python packages support for Python 2.7 is ending 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 2.7, or 3.6 or later is required to use this package.
  • An Azure subscription
  • An existing Text Analytics resource

Note: the new unified Cognitive Language Services are not currently available for deployment.

Install the package

Install the Azure Conversations client library for Python with pip:

pip install azure-ai-language-conversations

Authenticate the client

In order to interact with the CLU service, you'll need to create an instance of the ConversationAnalysisClient 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.

Get an API key

You can get the endpoint and an API key from the Cognitive Services resource in the Azure Portal.

Alternatively, use the Azure CLI command shown below to get the API key from the Cognitive Service resource.

az cognitiveservices account keys list --resource-group <resource-group-name> --name <resource-name>

Create ConversationAnalysisClient

Once you've determined your endpoint and API key you can instantiate a ConversationAnalysisClient:

from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<api-key>")
client = ConversationAnalysisClient(endpoint, credential)

Key concepts

ConversationAnalysisClient

The ConversationAnalysisClient is the primary interface for making predictions using your deployed Conversations models. For asynchronous operations, an async ConversationAnalysisClient is in the azure.ai.language.conversation.aio namespace.

Examples

The azure-ai-language-conversation client library provides both synchronous and asynchronous APIs.

The following examples show common scenarios using the client created above.

Analyze a conversation with a Conversation App

If you would like to extract custom intents and entities from a user utterance, you can call the client.analyze_conversations() method with your conversation's project name as follows:

# import libraries
import os
from azure.core.credentials import AzureKeyCredential

from azure.ai.language.conversations import ConversationAnalysisClient
from azure.ai.language.conversations.models import ConversationAnalysisOptions

# get secrets
conv_endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
conv_key = os.environ["AZURE_CONVERSATIONS_KEY"]
conv_project = os.environ["AZURE_CONVERSATIONS_PROJECT"]

# prepare data
query = "One california maki please."
input = ConversationAnalysisOptions(
    query=query
)

# analyze quey
client = ConversationAnalysisClient(conv_endpoint, AzureKeyCredential(conv_key))
with client:
    result = client.analyze_conversations(
        input,
        project_name=conv_project,
        deployment_name='production'
    )

# view result
print("query: {}".format(result.query))
print("project kind: {}\n".format(result.prediction.project_kind))

print("view top intent:")
print("\ttop intent: {}".format(result.prediction.top_intent))
print("\tcategory: {}".format(result.prediction.intents[0].category))
print("\tconfidence score: {}\n".format(result.prediction.intents[0].confidence_score))

print("view entities:")
for entity in result.prediction.entities:
    print("\tcategory: {}".format(entity.category))
    print("\ttext: {}".format(entity.text))
    print("\tconfidence score: {}".format(entity.confidence_score))

Analyze conversation with a Orchestration App

If you would like to pass the user utterance to your orchestrator (worflow) app, you can call the client.analyze_conversations() method with your orchestration's project name. The orchestrator project simply orchestrates the submitted user utterance between your language apps (Luis, Conversation, and Question Answering) to get the best response according to the user intent. See the next example:

# import libraries
import os
from azure.core.credentials import AzureKeyCredential

from azure.ai.language.conversations import ConversationAnalysisClient
from azure.ai.language.conversations.models import ConversationAnalysisOptions

# get secrets
conv_endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
conv_key = os.environ["AZURE_CONVERSATIONS_KEY"]
orchestration_project = os.environ["AZURE_CONVERSATIONS_WORKFLOW_PROJECT")

# prepare data
query = "How do you make sushi rice?",
input = ConversationAnalysisOptions(
    query=query
)

# analyze query
client = ConversationAnalysisClient(conv_endpoint, AzureKeyCredential(conv_key))
with client:
    result = client.analyze_conversations(
        input,
        project_name=orchestration_project,
        deployment_name='production',
    )

# view result
print("query: {}".format(result.query))
print("project kind: {}\n".format(result.prediction.project_kind))

print("view top intent:")
print("\ttop intent: {}".format(result.prediction.top_intent))
print("\tcategory: {}".format(result.prediction.intents[0].category))
print("\tconfidence score: {}\n".format(result.prediction.intents[0].confidence_score))

print("view Question Answering result:")
print("\tresult: {}\n".format(result.prediction.intents[0].result))

Analyze conversation with a Orchestration (Direct) App

If you would like to use an orchestrator (orchestration) app, and you want to call a specific one of your language apps directly, you can call the client.analyze_conversations() method with your orchestration's project name and the diirect target name which corresponds to your one of you language apps as follows:

# import libraries
import os
from azure.core.credentials import AzureKeyCredential

from azure.ai.language.conversations import ConversationAnalysisClient
from azure.ai.language.conversations.models import ConversationAnalysisOptions

# get secrets
conv_endpoint = os.environ["AZURE_CONVERSATIONS_ENDPOINT"]
conv_key = os.environ["AZURE_CONVERSATIONS_KEY"]
orchestration_project = os.environ["AZURE_CONVERSATIONS_WORKFLOW_PROJECT")

# prepare data
query = "How do you make sushi rice?",
target_intent = "SushiMaking"
input = ConversationAnalysisOptions(
    query=query,
    direct_target=target_intent,
    parameters={
        "SushiMaking": QuestionAnsweringParameters(
            calling_options={
                "question": query,
                "top": 1,
                "confidenceScoreThreshold": 0.1
            }
        )
    }
)

# analyze query
client = ConversationAnalysisClient(conv_endpoint, AzureKeyCredential(conv_key))
with client:
    result = client.analyze_conversations(
        input,
        project_name=orchestration_project,
        deployment_name='production',
    )

# view result
print("query: {}".format(result.query))
print("project kind: {}\n".format(result.prediction.project_kind))

print("view top intent:")
print("\ttop intent: {}".format(result.prediction.top_intent))
print("\tcategory: {}".format(result.prediction.intents[0].category))
print("\tconfidence score: {}\n".format(result.prediction.intents[0].confidence_score))

print("view Question Answering result:")
print("\tresult: {}\n".format(result.prediction.intents[0].result))

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

The Conversations client will raise exceptions defined in Azure Core.

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 full SDK logging documentation with examples here.

import sys
import logging
from azure.core.credentials import AzureKeyCredential
from azure.ai.language.conversations import ConversationAnalysisClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

endpoint = "https://<my-custom-subdomain>.cognitiveservices.azure.com/"
credential = AzureKeyCredential("<my-api-key>")

# This client will log detailed information about its HTTP sessions, at DEBUG level
client = ConversationAnalysisClient(endpoint, credential, logging_enable=True)
result = client.analyze_conversations(...)

Similarly, logging_enable can enable detailed logging for a single operation, even when it isn't enabled for the client:

result = client.analyze_conversations(..., logging_enable=True)

Next steps

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.

Impressions

Release History

1.0.0b1 (2021-11-03)

Features Added

  • Initial release

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-conversations-1.0.0b1.zip (78.9 kB view details)

Uploaded Source

Built Distribution

azure_ai_language_conversations-1.0.0b1-py2.py3-none-any.whl (32.9 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file azure-ai-language-conversations-1.0.0b1.zip.

File metadata

  • Download URL: azure-ai-language-conversations-1.0.0b1.zip
  • Upload date:
  • Size: 78.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.5.0 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

File hashes

Hashes for azure-ai-language-conversations-1.0.0b1.zip
Algorithm Hash digest
SHA256 7c7b6cec18a5016ffc73ba1c28d7cfef0cd957acb30357ab04a8511d403dfdbc
MD5 401960ea0d6e6380a7e5c34f5874ea5e
BLAKE2b-256 d061e5955539d921c6bea8daddacf918550bf2ed0bae2e45968eecf2942063ad

See more details on using hashes here.

File details

Details for the file azure_ai_language_conversations-1.0.0b1-py2.py3-none-any.whl.

File metadata

  • Download URL: azure_ai_language_conversations-1.0.0b1-py2.py3-none-any.whl
  • Upload date:
  • Size: 32.9 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.5.0 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

File hashes

Hashes for azure_ai_language_conversations-1.0.0b1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 3bab2d6fec0b9601a958f913d37d0df0ea818136ee155677188cc999beea331a
MD5 950d67118a3326061b8d690816b2178f
BLAKE2b-256 58062d471afd8e58468ee112258150dae24da57508c443a1509ecd87711194ef

See more details on using hashes here.

Supported by

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