Use the POP API to create business-specific hotwords

更新时间:
复制 MD 格式

Use the Alibaba Cloud POP (pctowap open platform) API to create, query, update, and delete business-specific hotword vocabularies for Intelligent Speech Interaction (ISI).

The following operations are available:

OperationDescription
CreateAsrVocabCreates a hotword vocabulary
GetAsrVocabQueries the details of a single hotword vocabulary
UpdateAsrVocabUpdates a hotword vocabulary
DeleteAsrVocabDeletes a hotword vocabulary
ListAsrVocabQueries hotword vocabularies by page

Limits

ConstraintValue
Hotword vocabularies per account10
Hotwords per vocabulary128
Maximum length per hotword10 Chinese characters
EncodingUTF-8
Allowed charactersNo punctuation or special characters
Weight rangeInteger in [-6, 5]

How hotword weights work

  • Positive weight: the higher the weight, the more likely the hotword is recognized.

  • Negative weight: the lower the weight, the more likely the hotword is suppressed.

  • Weight -6: the hotword is not recognized if possible.

  • Default recommendation: set the weight to 2.

Increasing a hotword's weight may reduce recognition accuracy for other hotwords. Adjust weights incrementally and test the results before deploying to production.

CreateAsrVocab

Creates a hotword vocabulary. A vocabulary is a collection of business-specific hotwords and their weights.

Request parameters

ParameterTypeRequiredDescription
NameStringYesThe name of the hotword vocabulary.
WordWeightsStringYesA JSON object mapping hotwords to their weights. Each key is a hotword (String) and each value is a weight (Int).
DescriptionStringNoThe description of the hotword vocabulary.

WordWeights example

{
    "Apple": 3,
    "Watermelon": 3
}

Response parameters

ParameterTypeDescription
RequestIdStringThe request ID.
VocabIdStringThe ID of the created hotword vocabulary. Use this ID to query, update, or delete the vocabulary.

Sample response

{
    "VocabId": "0074ac87db754e0fbd3465c60d86****",
    "RequestId": "77C00AE4-A646-4A41-B6FF-F06C19FA****"
}

HTTP status code 200 indicates success. For error codes, see Error codes.

GetAsrVocab

Queries the details of a hotword vocabulary by vocabulary ID, including its hotwords and weights.

Request parameters

ParameterTypeRequiredDescription
IdStringYesThe ID of the hotword vocabulary. The ID is generated when the vocabulary is created.

Response parameters

ParameterTypeDescription
RequestIdStringThe request ID.
VocabVocab objectThe hotword vocabulary details.

Vocab object parameters

ParameterTypeDescription
IdStringThe ID of the hotword vocabulary.
NameStringThe name of the hotword vocabulary.
DescriptionStringThe description of the hotword vocabulary.
SizeIntThe compiled size of the hotword vocabulary.
Md5StringThe MD5 hash of the compiled hotword vocabulary.
CreateTimeStringThe time when the hotword vocabulary was created.
UpdateTimeStringThe time when the hotword vocabulary was last updated.
WordWeightsMapThe hotwords and their weights.

Sample response

{
    "RequestId": "A590423E-FEBC-4AA0-A520-4DA77292****",
    "Vocab": {
        "Name": "Test vocabulary",
        "Md5": "58c732d3b31eb564c275371d46fc****",
        "Description": "Test description",
        "CreateTime": "2018-11-26 17:19:40",
        "UpdateTime": "2018-11-26 17:19:40",
        "Id": "6118b2a057d1440bb253382a7617****",
        "WordWeights": {
            "Watermelon": 3,
            "Apple": 3
        },
        "Size": 323
    }
}

HTTP status code 200 indicates success. For error codes, see Error codes.

UpdateAsrVocab

Updates a hotword vocabulary by vocabulary ID. Updatable fields include the vocabulary name, description, hotwords, and weights.

Request parameters

ParameterTypeRequiredDescription
IdStringYesThe ID of the hotword vocabulary to update.
NameStringYesThe new name of the hotword vocabulary.
WordWeightsStringYesA JSON object mapping the new hotwords to their weights.
DescriptionStringNoThe new description of the hotword vocabulary.

Response parameters

ParameterTypeDescription
RequestIdStringThe request ID.

Sample response

{
    "RequestId": "829E373C-9E23-4DEF-A979-002F140B****"
}

HTTP status code 200 indicates success. For error codes, see Error codes.

DeleteAsrVocab

Deletes a hotword vocabulary by vocabulary ID.

Request parameters

ParameterTypeRequiredDescription
IdStringYesThe ID of the hotword vocabulary to delete.

Response parameters

ParameterTypeDescription
RequestIdStringThe request ID.

Sample response

{
    "RequestId": "75CCBD40-BC19-4227-9140-0F42806BBF6F"
}

HTTP status code 200 indicates success. For error codes, see Error codes.

ListAsrVocab

Queries hotword vocabularies by page, sorted in descending order by last update time.

The response does not include hotwords or weights (WordWeights) to prevent oversized payloads. To retrieve hotwords and weights for a specific vocabulary, call GetAsrVocab.

Request parameters

ParameterTypeRequiredDescription
PageNumberIntNoThe page number to return. Must be a positive integer. Default: 1.
PageSizeIntNoThe number of vocabularies per page. Valid values: 10 to 100. Default: 10.
To avoid response bodies large enough to be intercepted by a gateway or proxy, request one page at a time. If the number of vocabularies on the requested page is less than PageSize, all remaining vocabularies are returned.

Response parameters

ParameterTypeDescription
RequestIdStringThe request ID.
PagePage objectThe paginated vocabulary results.

Page object parameters

ParameterTypeDescription
ContentList\<Vocab\>The list of hotword vocabularies. Each item contains the same fields as a Vocab object, excluding WordWeights.
PageNumberIntThe page number of the returned results.
PageSizeIntThe number of vocabularies returned per page.
TotalPagesIntThe total number of pages.
TotalItemsIntThe total number of hotword vocabularies.

Sample response

{
    "Page": {
        "PageNumber": 1,
        "PageSize": 10,
        "TotalItems": 5,
        "TotalPages": 1,
        "Content": [
            {
                "Name": "Test vocabulary_1",
                "Md5": "eafaaf1d73b17c9d35c64d600e07****",
                "Description": "Test description_1",
                "CreateTime": "2018-11-26 17:51:41",
                "UpdateTime": "2018-11-26 17:51:41",
                "Id": "266df2819a9d4d96a07c5c5d39b6****",
                "Size": 323
            },
            {
                "Name": "Test vocabulary_2",
                "Md5": "f32c10fd8569cb3712576a0ea988****",
                "Description": "Test description_2",
                "CreateTime": "2018-11-26 17:51:41",
                "UpdateTime": "2018-11-26 17:51:41",
                "Id": "0fa718759c034f67bb3e394d2fd9****",
                "Size": 323
            }
        ]
    },
    "RequestId": "CB7B4AB4-5C16-4617-8B91-519A130E****"
}

HTTP status code 200 indicates success. For error codes, see Error codes.

Error codes

If the HTTP status code is not 200, the request failed. The response body contains a JSON object with error details.

Error codeDescriptionResolution
SLP.PAGE_NUMBER_INVALIDThe PageNumber value is invalid.Set PageNumber to an integer greater than or equal to 1.
SLP.PAGE_SIZE_INVALIDThe PageSize value is invalid.Set PageSize to an integer in the range [10, 100].
SLP.NOT_FOUNDThe specified vocabulary ID does not exist.Verify the vocabulary ID.
SLP.PARAMETER_ERROROne or more request parameters are invalid.Check the error message for details on which parameter is invalid.
SLP.EXCEED_LIMITThe number of hotword vocabularies has reached the limit of 10.Delete an existing vocabulary before creating a new one.
SLP.ASR_VOCAB_ERRORA vocabulary error other than those listed above occurred.Check the error message for details.

Sample error response

{
    "RequestId": "848C33E3-5A74-4BF8-9BE6-B78576C6****",
    "HostId": "nls-slp.ap-southeast-1.aliyuncs.com",
    "Code": "SLP.EXCEED_LIMIT",
    "Message": "Vocab count has reached the limit! (max: 10)"
}

Sample code

The following example uses the CommonRequest method of Alibaba Cloud SDK for Java to send POP API requests in remote procedure call (RPC) style.

Prerequisites

Add the following dependencies to your Maven project. The SDK core version must be 3.5.0 or later. Version 4.0.0 and later require additional third-party libraries — follow the prompts.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>3.7.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>

For more information, see Get started with Alibaba Cloud Classic SDK for Java and Use CommonRequest.

Java example

All examples below use the CommonRequest method to call the POP API. The client is authenticated using an AccessKey ID and AccessKey secret passed as command-line arguments.

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AsrVocabPopApiDemo {

    // Region and endpoint constants — do not modify.
    private static final String REGION_ID = "ap-southeast-1";
    private static final String DOMAIN = "nls-slp.ap-southeast-1.aliyuncs.com";
    private static final ProtocolType PROTOCOL_TYPE = ProtocolType.HTTPS;

    // POP API constants — do not modify.
    private static final String API_VERSION = "2018-11-20";
    private static final String ACTION_CREATE_ASR = "CreateAsrVocab";
    private static final String ACTION_GET_ASR_VOCAB = "GetAsrVocab";
    private static final String ACTION_LIST_ASR_VOCAB = "ListAsrVocab";
    private static final String ACTION_UPDATE_ASR_VOCAB = "UpdateAsrVocab";
    private static final String ACTION_DELETE_ASR_VOCAB = "DeleteAsrVocab";

    // Parameter key constants — do not modify.
    private static final String KEY_VOCAB_ID = "VocabId";
    private static final String KEY_ID = "Id";
    private static final String KEY_NAME = "Name";
    private static final String KEY_DESCRIPTION = "Description";
    private static final String KEY_WORD_WEIGHTS = "WordWeights";
    private static final String KEY_VOCAB = "Vocab";
    private static final String KEY_PAGE = "Page";
    private static final String KEY_PAGE_NUMBER = "PageNumber";
    private static final String KEY_PAGE_SIZE = "PageSize";

    private static IAcsClient client;

    static class Vocab {
        public String Id;
        public String Name;
        public String Description;
        public int Size;
        public String Md5;
        public String CreateTime;
        public String UpdateTime;
        public Map<String, Integer> WordWeights = new HashMap<String, Integer>();
    }

    static class Page {
        class VocabContent {
            public String Id;
            public String Name;
            public String Description;
            public int Size;
            public String Md5;
            public String CreateTime;
            public String UpdateTime;
        }
        public int PageNumber;
        public int PageSize;
        public int TotalItems;
        public int TotalPages;
        public List<VocabContent> Content = new ArrayList<VocabContent>();
    }

    public AsrVocabPopApiDemo(String akId, String akSecret) {
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID, akId, akSecret);
        client = new DefaultAcsClient(profile);
    }

    private CommonRequest newRequest(String action) {
        CommonRequest request = new CommonRequest();
        request.setDomain(DOMAIN);
        request.setProtocol(PROTOCOL_TYPE);
        request.setVersion(API_VERSION);
        request.setMethod(MethodType.POST);
        request.setAction(action);
        return request;
    }

    /**
     * Creates a hotword vocabulary.
     *
     * @param name        Required. The vocabulary name.
     * @param description Optional. The vocabulary description.
     * @param wordWeights Required. JSON map of hotwords and their weights.
     * @return The vocabulary ID, or null if creation failed.
     */
    String createAsrVocab(String name, String description, String wordWeights) {
        CommonRequest request = newRequest(ACTION_CREATE_ASR);
        request.putBodyParameter(KEY_NAME, name);
        request.putBodyParameter(KEY_DESCRIPTION, description);
        request.putBodyParameter(KEY_WORD_WEIGHTS, wordWeights);
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (response.getHttpStatus() != 200) {
            System.out.println(response.getData());
            System.out.println("Failed to create hotword vocabulary. HTTP status: " + response.getHttpStatus());
            return null;
        }
        JSONObject result = JSONObject.parseObject(response.getData());
        return result.getString(KEY_VOCAB_ID);
    }

    /**
     * Queries the details of a hotword vocabulary.
     *
     * @param vocabId The vocabulary ID.
     * @return The Vocab object, or null if the query failed.
     */
    Vocab getAsrVocab(String vocabId) {
        CommonRequest request = newRequest(ACTION_GET_ASR_VOCAB);
        request.putBodyParameter(KEY_ID, vocabId);
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (response.getHttpStatus() != 200) {
            System.out.println(response.getData());
            System.out.println("Failed to query hotword vocabulary. HTTP status: " + response.getHttpStatus());
            return null;
        }
        JSONObject result = JSONObject.parseObject(response.getData());
        String vocabJson = result.getString(KEY_VOCAB);
        return JSONObject.parseObject(vocabJson, Vocab.class);
    }

    /**
     * Updates a hotword vocabulary.
     *
     * @param vocabId     The vocabulary ID.
     * @param name        The new vocabulary name.
     * @param description The new vocabulary description.
     * @param wordWeights JSON map of the new hotwords and their weights.
     * @return true if the update succeeded, false otherwise.
     */
    boolean updateAsrVocab(String vocabId, String name, String description, String wordWeights) {
        CommonRequest request = newRequest(ACTION_UPDATE_ASR_VOCAB);
        request.putBodyParameter(KEY_ID, vocabId);
        request.putBodyParameter(KEY_NAME, name);
        request.putBodyParameter(KEY_DESCRIPTION, description);
        request.putBodyParameter(KEY_WORD_WEIGHTS, wordWeights);
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (response.getHttpStatus() != 200) {
            System.out.println(response.getData());
            System.out.println("Failed to update hotword vocabulary. HTTP status: " + response.getHttpStatus());
            return false;
        }
        return true;
    }

    /**
     * Deletes a hotword vocabulary.
     *
     * @param vocabId The vocabulary ID.
     * @return true if the deletion succeeded, false otherwise.
     */
    boolean deleteAsrVocab(String vocabId) {
        CommonRequest request = newRequest(ACTION_DELETE_ASR_VOCAB);
        request.putBodyParameter(KEY_ID, vocabId);
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (response.getHttpStatus() != 200) {
            System.out.println(response.getData());
            System.out.println("Failed to delete hotword vocabulary. HTTP status: " + response.getHttpStatus());
            return false;
        }
        return true;
    }

    /**
     * Queries hotword vocabularies. Defaults to page 1 with 10 results per page.
     * WordWeights are not included in the response — call GetAsrVocab for full details.
     *
     * @return The Page object, or null if the query failed.
     */
    Page listAsrVocab() {
        CommonRequest request = newRequest(ACTION_LIST_ASR_VOCAB);
        request.putBodyParameter(KEY_PAGE_NUMBER, 1);
        request.putBodyParameter(KEY_PAGE_SIZE, 10);
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (response.getHttpStatus() != 200) {
            System.out.println(response.getData());
            System.out.println("Failed to query hotword vocabularies. HTTP status: " + response.getHttpStatus());
            return null;
        }
        JSONObject result = JSONObject.parseObject(response.getData());
        String pageJson = result.getString(KEY_PAGE);
        return JSONObject.parseObject(pageJson, Page.class);
    }

    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("Usage: AsrVocabPopApiDemo <AccessKey ID> <AccessKey secret>");
            return;
        }
        String accessKeyId = args[0];
        String accessKeySecret = args[1];
        AsrVocabPopApiDemo demo = new AsrVocabPopApiDemo(accessKeyId, accessKeySecret);

        // Create a hotword vocabulary.
        String name = "Test vocabulary";
        String description = "Test description";
        String wordWeights = "{\"Apple\": 3, \"Watermelon\": 3}";
        String vocabId = demo.createAsrVocab(name, description, wordWeights);
        if (vocabId != null) {
            System.out.println("Vocabulary created. ID: " + vocabId);
        } else {
            System.out.println("Failed to create vocabulary.");
            return;
        }

        // Query the vocabulary.
        Vocab vocab = demo.getAsrVocab(vocabId);
        if (vocab != null) {
            System.out.println("Vocabulary details: " + JSONObject.toJSONString(vocab));
        } else {
            System.out.println("Failed to query vocabulary.");
        }

        // Update the vocabulary.
        name = "Test vocabulary 2";
        description = "Test description 2";
        wordWeights = "{\"Apple\": 2, \"Watermelon\": 2}";
        boolean isUpdated = demo.updateAsrVocab(vocabId, name, description, wordWeights);
        if (isUpdated) {
            System.out.println("Vocabulary updated: " + JSONObject.toJSONString(demo.getAsrVocab(vocabId)));
        } else {
            System.out.println("Failed to update vocabulary.");
        }

        // Delete the vocabulary.
        boolean isDeleted = demo.deleteAsrVocab(vocabId);
        if (isDeleted) {
            System.out.println("Vocabulary deleted.");
        } else {
            System.out.println("Failed to delete vocabulary.");
        }

        // Create multiple vocabularies and query them.
        for (int i = 0; i < 10; i++) {
            name = "Test vocabulary_" + i;
            description = "Test description_" + i;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Apple", 2);
            jsonObject.put("Watermelon", 2);
            wordWeights = jsonObject.toJSONString();
            demo.createAsrVocab(name, description, wordWeights);
        }

        Page page = demo.listAsrVocab();
        if (page != null) {
            System.out.println("Vocabularies on page 1: " + JSONObject.toJSONString(page));
        } else {
            System.out.println("Failed to list vocabularies.");
            return;
        }

        // Delete all vocabularies on the page.
        for (int i = 0; i < page.Content.size(); i++) {
            demo.deleteAsrVocab(page.Content.get(i).Id);
        }
        page = demo.listAsrVocab();
        if (page != null) {
            System.out.println("Remaining vocabularies: " + JSONObject.toJSONString(page));
        }
    }
}