创建Token
历史文档仅适用于百炼1.0版本的API和SDK调用,鉴于旧版功能已停止迭代更新,强烈建议您升级至最新版API和SDK,具体详情请参考新版本升级说明。
新版应用调用文档:应用调用。
本节主要介绍如何创建Token,来调用文本生成API。同时,在第4节,提供主流开发语言的调用示例代码,包括Java、Python、Go、C#和Nodejs语言。
功能描述
通过AccessKey、Access Secret Key和Agent Key生成Token。此token在Completion API调用时会用到。
当前API需要参考V3版本请求体&签名机制,进行签名再请求,有一定的复杂性,因此建议直接参考第4节《调用代码示例》。
前提条件
首先,请参考文档AccessKey、AppID及AgentKey获取方式获取AK/SK、Agent Key和AppId。如果是RAM账号,请参考文档如何使用业务空间中的RAM账号使用方式。
API详情
创建文本生成访问接口的API token。
协议:HTTP
请求方式:POST
请求地址:https://bailian.cn-beijing.aliyuncs.com
请求参数:
参数名 | 参数类型 | 是否必填 | 说明 |
Request Heders | |||
AgentKey | string | 是 | 业务空间标识,请参照section#2获取业务空间标识 |
响应参数:
字段名 | 字段类型 | 说明 | |
Success | boolean | 是否成功(true:成功,false:失败) | |
Code | string | 错误代码 | |
Message | string | 错误消息 | |
RequestId | string | 请求唯一标识 | |
Data | Data | 文本生成结果 | |
Data | |||
Token | string | 临时访问令牌 | |
ExpiredTime | long | 令牌到期时间, unix时间戳,如1687227783 |
注:在调用后续API时,需将token保存在本地,在过期前10分钟重新获取token,以免每次调用产生token造成性能问题。
调用代码示例
主流的开发语言生成token的调用代码示例,包括Java、Python、Go、C#、Nodejs等。
# 1. 获取和安装sdk
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>bailian20230601</artifactId>
<version>1.1.2</version>
</dependency>
# 2. 调用代码示例
import com.aliyun.bailian20230601.Client;
import com.aliyun.bailian20230601.models.CreateTokenRequest;
import com.aliyun.bailian20230601.models.CreateTokenResponse;
import com.aliyun.bailian20230601.models.CreateTokenResponseBody;
import com.aliyun.broadscope.bailian.sdk.BaiLianSdkException;
import com.aliyun.teaopenapi.models.Config;
import org.apache.commons.lang3.StringUtils;
public void createToken() {
String accessKeyId = System.getenv("ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ACCESS_KEY_SECRET");
String agentKey = System.getenv("AGENT_KEY");
String endpoint = "bailian.cn-beijing.aliyuncs.com";
Config config = new Config().setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret)
.setEndpoint(endpoint);
try {
Client client = new Client(config);
CreateTokenRequest request = new CreateTokenRequest().setAgentKey(agentKey);
CreateTokenResponse response = client.createToken(request);
CreateTokenResponseBody body = response.getBody();
if (body == null) {
String error = "create token error";
throw new RuntimeException(error);
}
if (!body.success) {
String requestId = body.requestId;
if (StringUtils.isBlank(requestId)) {
requestId = response.getHeaders().get("x-acs-request-id");
}
String error = "failed to create token, reason: " + body.message + " RequestId: " + requestId;
throw new RuntimeException(error);
}
CreateTokenResponseBody.CreateTokenResponseBodyData data = body.getData();
if (data == null) {
throw new RuntimeException("create token error, data is null");
}
System.out.printf("token: %s, expiredTime : %d", data.getToken(), data.getExpiredTime());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
# 1. 获取和安装SDK
pip install broadscope-bailian
# 2. 调用代码示例
import os
from alibabacloud_bailian20230601.client import Client
from alibabacloud_bailian20230601.models import CreateTokenRequest
from alibabacloud_tea_openapi.models import Config
def create_token():
access_key_id = os.environ.get("ACCESS_KEY_ID")
access_key_secret = os.environ.get("ACCESS_KEY_SECRET")
agent_key = os.environ.get("AGENT_KEY")
endpoint = "bailian.cn-beijing.aliyuncs.com"
config = Config(access_key_id=access_key_id,
access_key_secret=access_key_secret,
endpoint=endpoint)
client = Client(config=config)
token_response = client.create_token(CreateTokenRequest(agent_key=agent_key))
if token_response.status_code != 200 or token_response.body is None:
raise RuntimeError("create token error, code=%d" % token_response.status_code)
token_body = token_response.body
if not token_body.success:
request_id = token_body.request_id
if not request_id:
request_id = token_response.headers.get("x-acs-request-id")
raise RuntimeError("create token error, code=%s, message=%s RequestId: %s"
% (token_body.code, token_body.message, request_id))
print('token: %s, expired_time: %s' % (token_body.data.token, token_body.data.expired_time))
1. 获取和安装SDK
go get github.com/alibabacloud-go/bailian-20230601
go get github.com/alibabacloud-go/darabonba-openapi/v2
2. 调用代码示例
import (
"fmt"
apiClient "github.com/alibabacloud-go/bailian-20230601/client"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
"os"
)
func CreateToken() {
accessKeyId := os.Getenv("ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ACCESS_KEY_SECRET")
agentKey := os.Getenv("AGENT_KEY")
endpoint := "bailian.cn-beijing.aliyuncs.com"
config := &openapi.Config{AccessKeyId: &accessKeyId,
AccessKeySecret: &accessKeySecret,
Endpoint: &endpoint}
tokenClient, err := apiClient.NewClient(config)
if err != nil {
fmt.Printf("failed to new client, err: %v\n", err)
return
}
request := &apiClient.CreateTokenRequest{AgentKey: &agentKey}
result, err := tokenClient.CreateToken(request)
if err != nil {
fmt.Printf("failed to create token, err: %v\n", err)
return
}
resultBody := result.Body
if !(*resultBody.Success) {
requestId := resultBody.RequestId
if requestId == nil {
requestId = result.Headers["x-acs-request-id"]
}
errMessage := fmt.Sprintf("Failed to create token, reason: %s RequestId: %s", *resultBody.Message, *requestId)
fmt.Printf("%v\n", errMessage)
}
fmt.Printf("token: %s, expiredTime : %d\n", *resultBody.Data.Token, *resultBody.Data.ExpiredTime)
}
1. 获取和安装SDK
dotnet add package AlibabaCloud.SDK.Bailian20230601
2. 调用代码示例
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Bailian20230601;
using AlibabaCloud.SDK.Bailian20230601.Models;
public void createToken()
{
String accessKeyId = Environment.GetEnvironmentVariable("ACCESS_KEY_ID");
String accessKeySecret = Environment.GetEnvironmentVariable("ACCESS_KEY_SECRET");
String agentKey = Environment.GetEnvironmentVariable("AGENT_KEY");
String endpoint = "bailian.cn-beijing.aliyuncs.com";
Config config = new Config();
config.AccessKeyId = accessKeyId;
config.AccessKeySecret = accessKeySecret;
config.Endpoint = "bailian.cn-beijing.aliyuncs.com";
Client client = new Client(config);
CreateTokenRequest request = new CreateTokenRequest();
request.AgentKey = agentKey;
CreateTokenResponse response = client.CreateToken(request);
CreateTokenResponseBody body = response.Body;
if (body == null)
{
throw new ApplicationException("create token error");
}
if (body.Success != true)
{
String requestId = body.RequestId;
if (requestId == null)
{
requestId = response.Headers["x-acs-request-id"];
}
String error = body.Message + ", requestId: " + requestId;
throw new ApplicationException(error);
}
CreateTokenResponseBody.CreateTokenResponseBodyData data = body.Data;
if (data == null)
{
throw new ApplicationException("create token error, data is null");
}
Console.WriteLine("token: {0}, expired time: {1}", data.Token, data.ExpiredTime);
}
1. 获取和安装sdk
npm install @alicloud/bailian20230601 -S
2. 调用代码示例
const Client = require("@alicloud/bailian20230601").default;
const accessKeyId = process.env.ACCESS_KEY_ID;
const accessKeySecret = process.env.ACCESS_KEY_SECRET;
const agentkey = process.env.AGENT_KEY;
const endpoint = 'bailian.cn-beijing.aliyuncs.com'
const c = new Client({
accessKeyId: accessKeyId,
accessKeySecret: accessKeySecret,
endpoint: endpoint
})
async function createToken() {
try {
const response = await c.createToken(
{agentKey: agentkey}
);
const responseBody = response.body
if (responseBody === null) {
throw new Error('failed to create token')
}
if (responseBody.success !== true) {
let requestId = responseBody.requestId;
if (requestId == null) {
requestId = response.headers["x-acs-request-id"];
}
let error = "failed to create token " + responseBody.message + ", requestId: " + requestId;
throw new Error(error)
}
const data = responseBody.data
if (data === null) {
throw new Error("failed to create token");
}
console.log('token: ' + data.token + ', expiredTime: ' + data.expiredTime);
} catch (err) {
console.log('failed to create token, err: ', err);
}
}
createToken().then(r => {
}).catch(err => {
console.error(err)
});