接口为:百度 ERNIE-Bot-4(邀测) 控制台直达链接
Javascript
const AK = "ur AK"
const SK = "ur SK"
const axios = require("axios").default;
let access_token = "ur token"
var url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=' + access_token
var params = JSON.stringify({
'messages': [
{ "role": "user", "content": "假设你是个程序员,你的名字是'就你叫夏洛啊',我的问题是:你的名字" },
]
})
var headers = { headers: { 'Content-Type': 'application/json' } }
async function main() {
axios.post(url, params, headers
).then(function (response) {
console.log("#>> then", response.data);
}).catch(function (error) {
console.log("#>> catch", error);
});
}
function getAccessToken() {
let options = {
'method': 'POST',
'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
}
return axios(options).then((res) => {
refresh_token = res.data.refresh_token
access_token = res.data.access_token
return access_token
})
}
main();
在 axios.post().then() 的回调中返回请求结果:
Python
"""
注意事项:
1. 需要安装 requests,命令:pip install requests
"""
import requests
import json
API_KEY = "ur API_KEY"
SECRET_KEY = "ur SECRET_KEY"
access_token = "ur access_token"
def main():
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + access_token
payload = json.dumps({
"messages": [
{ "role": "user", "content": "假设你是个程序员,你的名字是'就你叫夏洛啊',我的题是:你的名字" },
]
})
headers = {'Content-Type': 'application/json'}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
def get_access_token():
"""
使用 AK,SK 生成鉴权签名(Access Token)
:return: access_token,或是None(如果错误)
"""
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
return str(requests.post(url, params=params).json().get("access_token"))
if __name__ == '__main__':
main()
以下是返回的请求结果: