Go SDK
This topic describes how to use the Go software development kit (SDK) for the Natural Language Processing (NLP) Self-Learning Platform. This topic also describes how to create an asynchronous prediction task and obtain the prediction results. Complete code samples are provided.
Prerequisites
An AccessKey is required to call Alibaba Cloud OpenAPI operations. If you do not have an AccessKey, create one. For more information, see Create an AccessKey. To prevent credential leaks, we recommend that you configure your AccessKey using environment variables. For more information about security, see Best practices for using access credentials to access Alibaba Cloud OpenAPI.
Environment requirements
Go 1.10.x or later.
Step 1: Import the SDK
The Alibaba Cloud SDK supports both generalized and specialized calls to invoke OpenAPI operations. The SDKs that you need to import vary based on the call method. For more information, see Generalized calls and specialized calls.
Specialized calls
In OpenAPI Explorer, you can search for a product to view the supported SDK languages and installation methods. To obtain the SDK for this example, perform the following steps:
In the All Languages section, select your preferred SDK language.
You can select your preferred Installation Method and copy the code into your project.
Load the dependency package in your project.
Use the following installation method:
go get github.com/alibabacloud-go/nlp-automl-20191111Generalized calls
The generalized call method does not depend on a specific product SDK. You only need to import the following core package: github.com/alibabacloud-go/darabonba-openapi/v2/client. To install the package for Go, run the following command. For the latest version, see darabonba-openapi.
go get github.com/alibabacloud-go/darabonba-openapi/v2/clientStep 2: Initialize the client
Specify the endpoint of the NLP Self-Learning Platform based on the region. For more information about endpoints, see Supported regions.
The following code sample shows how to make a specialized call. For information about how to make a generalized call, see Generalized calls and specialized calls.
Initialize using an AccessKey
The AccessKey of an Alibaba Cloud account has permissions to access all API operations. We recommend that you use a Resource Access Management (RAM) user to make API calls or perform routine O&M. Do not hard-code your AccessKey ID and AccessKey secret in your project code. Hard-coding your credentials may cause your AccessKey to be leaked, which compromises the security of all resources in your account.
This example shows how to authenticate a request by configuring the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
For more information about how to configure authentication information, see Manage access credentials.
The method for configuring environment variables varies by operating system. For more information, see Configure environment variables on Linux, macOS, and Windows.
import (
"encoding/json"
"strings"
"fmt"
"os"
nlp_automl20191111 "github.com/alibabacloud-go/nlp-automl-20191111/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
// Description:
//
// Initialize the client with an AccessKey ID and AccessKey secret.
//
// @return Client
//
// @throws Exception
func CreateClient () (_result *nlp_automl20191111.Client, _err error) {
// Hard-coding an AccessKey pair in your code may lead to an AccessKey leak and compromise the security of all resources in your account. The following code is for reference only.
// Use a more secure method, such as Security Token Service (STS), for authentication. For more information about authentication methods, see https://help.aliyun.com/document_detail/378661.html.
config := &openapi.Config{
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// For the endpoint, see https://api.aliyun.com/product/nlp-automl
config.Endpoint = tea.String("nlp-automl.cn-hangzhou.aliyuncs.com")
_result = &nlp_automl20191111.Client{}
_result, _err = nlp_automl20191111.NewClient(config)
return _result, _err
}Step 3: Use the initialized client to call an NLP Self-Learning Platform API
After you initialize the client, you can use it to call the APIs of the NLP Self-Learning Platform.
API operation: CreateAsyncPredict
You can call this operation to create an asynchronous prediction task. When you call this operation, you must create a request object and set the required parameters. You can also specify runtime configurations.
// Create a request object.
createAsyncPredictRequest := &nlp_automl20191111.CreateAsyncPredictRequest{
// The model ID. This parameter is not required when you create an asynchronous prediction based on the service name and service edition. Otherwise, this parameter is required.
ModelId: tea.Int32(1),
// The content to predict. The maximum length is 1,024 bytes.
Content: tea.String("National overall plan for land use"),
}
// Runtime configurations.
runtime := &util.RuntimeOptions{}The following code example shows how to create a flow using an AK:
package main
import (
"encoding/json"
"strings"
"fmt"
"os"
nlp_automl20191111 "github.com/alibabacloud-go/nlp-automl-20191111/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
// Description:
//
// Initialize the client with an AccessKey ID and AccessKey secret.
//
// @return Client
//
// @throws Exception
func CreateClient () (_result *nlp_automl20191111.Client, _err error) {
// Hard-coding an AccessKey pair in your code may lead to an AccessKey leak and compromise the security of all resources in your account. The following code is for reference only.
// Use a more secure method, such as Security Token Service (STS), for authentication. For more information about authentication methods, see https://help.aliyun.com/document_detail/378661.html.
config := &openapi.Config{
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// For the endpoint, see https://api.aliyun.com/product/nlp-automl
config.Endpoint = tea.String("nlp-automl.cn-hangzhou.aliyuncs.com")
_result = &nlp_automl20191111.Client{}
_result, _err = nlp_automl20191111.NewClient(config)
return _result, _err
}
func _main (args []*string) (_err error) {
client, _err := CreateClient()
if _err != nil {
return _err
}
// Create a request object.
createAsyncPredictRequest := &nlp_automl20191111.CreateAsyncPredictRequest{
// The model ID. This parameter is not required when you create an asynchronous prediction based on the service name and service edition. Otherwise, this parameter is required.
ModelId: tea.Int32(1),
// The content to predict. The maximum length is 1,024 bytes.
Content: tea.String("National overall plan for land use"),
}
// Runtime configurations.
runtime := &util.RuntimeOptions{}
tryErr := func()(_e error) {
defer func() {
if r := tea.Recover(recover()); r != nil {
_e = r
}
}()
// To run this code, copy it and add a print statement for the API return value.
_, _err = client.CreateAsyncPredictWithOptions(createAsyncPredictRequest, runtime)
if _err != nil {
return _err
}
return nil
}()
if tryErr != nil {
var error = &tea.SDKError{}
if _t, ok := tryErr.(*tea.SDKError); ok {
error = _t
} else {
error.Message = tea.String(tryErr.Error())
}
// This section is for printing and display purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
// Error message
fmt.Println(tea.StringValue(error.Message))
// Diagnosis address
var data interface{}
d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
d.Decode(&data)
if m, ok := data.(map[string]interface{}); ok {
recommend, _ := m["Recommend"]
fmt.Println(recommend)
}
_, _err = util.AssertAsString(error.Message)
if _err != nil {
return _err
}
}
return _err
}
func main() {
err := _main(tea.StringSlice(os.Args[1:]))
if err != nil {
panic(err)
}
}API operation: GetAsyncPredict
This API operation retrieves the result of an asynchronous prediction. When you call this operation, create a request object and set the necessary parameters and runtime configurations. The runtime configurations are also customizable.
// Create a request object.
getAsyncPredictRequest := &nlp_automl20191111.GetAsyncPredictRequest{
// The asynchronous prediction ID. Obtain this ID by calling the CreateAsyncPredict operation.
AsyncPredictId: tea.Int32(1629),
}
// Runtime configurations.
runtime := &util.RuntimeOptions{}The following is a complete code example of how to retrieve information about a flow using an AccessKey (AK):
// This file is auto-generated, don't edit it. Thanks.
package main
import (
"encoding/json"
"strings"
"fmt"
"os"
nlp_automl20191111 "github.com/alibabacloud-go/nlp-automl-20191111/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
// Description:
//
// Initialize the client with an AccessKey ID and AccessKey secret.
//
// @return Client
//
// @throws Exception
func CreateClient () (_result *nlp_automl20191111.Client, _err error) {
// Hard-coding an AccessKey pair in your code may lead to an AccessKey leak and compromise the security of all resources in your account. The following code is for reference only.
// Use a more secure method, such as Security Token Service (STS), for authentication. For more information about authentication methods, see https://help.aliyun.com/document_detail/378661.html.
config := &openapi.Config{
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set.
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// For the endpoint, see https://api.aliyun.com/product/nlp-automl
config.Endpoint = tea.String("nlp-automl.cn-hangzhou.aliyuncs.com")
_result = &nlp_automl20191111.Client{}
_result, _err = nlp_automl20191111.NewClient(config)
return _result, _err
}
func _main (args []*string) (_err error) {
client, _err := CreateClient()
if _err != nil {
return _err
}
// Create a request object.
getAsyncPredictRequest := &nlp_automl20191111.GetAsyncPredictRequest{
// The asynchronous prediction ID. Obtain this ID by calling the CreateAsyncPredict operation.
AsyncPredictId: tea.Int32(1629),
}
// Runtime configurations.
runtime := &util.RuntimeOptions{}
tryErr := func()(_e error) {
defer func() {
if r := tea.Recover(recover()); r != nil {
_e = r
}
}()
// To run this code, copy it and add a print statement for the API return value.
_, _err = client.GetAsyncPredictWithOptions(getAsyncPredictRequest, runtime)
if _err != nil {
return _err
}
return nil
}()
if tryErr != nil {
var error = &tea.SDKError{}
if _t, ok := tryErr.(*tea.SDKError); ok {
error = _t
} else {
error.Message = tea.String(tryErr.Error())
}
// This section is for printing and display purposes only. Handle exceptions with care. Do not ignore exceptions in your project.
// Error message
fmt.Println(tea.StringValue(error.Message))
// Diagnosis address
var data interface{}
d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
d.Decode(&data)
if m, ok := data.(map[string]interface{}); ok {
recommend, _ := m["Recommend"]
fmt.Println(recommend)
}
_, _err = util.AssertAsString(error.Message)
if _err != nil {
return _err
}
}
return _err
}
func main() {
err := _main(tea.StringSlice(os.Args[1:]))
if err != nil {
panic(err)
}
}SDK call examples
You can use the multi-language SDK demos to test the API. For sample code, see OpenAPI Explorer or .