Baidu API call (6)-call Baidu UNIT dialogue robot

1. Function description

  Call your own custom robot interface in Baidu UNIT platform to realize human-computer interaction

Two, create a robot application

(You can set the robot function according to your own needs)
1. How to create a robot: refer to the official tutorial
2. Make a weather-checking robot ( tutorial )
Function brief:
You can define your own word slot, define your own reply value, but you can use this Time limit (500 trials, it seems not enough)

Tutorial content supplement: You
need to add the last skills to the robot before they can be called
Insert picture description here
Insert picture description here

2. Add the UNIT function to the original speech recognition application (or open a new application directly)

(Application list—>Voice recognition management—>Edit—>Just add a UNIT)

Three, python calls Baidu dialogue robot

Refer to the technical documentation, you
need to call the required robot to modify the robot ID.
Insert picture description here

Four, use cases

The code has comments to help readers understand

# 说明:将固定文本发送给百度平台实现UNIT的交流

import requests
import json

# 需要的库requests、json(import 进来就好了)
baidu_server = 'https://aip.baidubce.com/oauth/2.0/token?'  #获取token的server
grant_type = 'client_credentials'
client_id = '' #API KEY
client_secret = '' #Secret KEY   这里可以自己去百度注册,这里是我的API KEY 和 Secret KEY

#合成请求token的url
url = baidu_server+'grant_type='+grant_type+'&client_id='+client_id+'&client_secret='+client_secret

#获取token
res = requests.get(url).text
data = json.loads(res)  #将json格式转换为字典格式
token = data['access_token']

access_token = token
q = "北京的天气"   #需要发送给UNIT服务器的内容放到这里即可
url = 'https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=' + access_token    #不用动
post_data = "{\"log_id\":\"UNITTEST_10000\",\"version\":\"2.0\",\"service_id\":\"S46420\",\"session_id\":\"\",\"request\":{\"query\":\"%s\",\"user_id\":\"88888\",\"query_info\":{\"type\":\"TEXT\",\"source\":\"KEYBOARD\"}}}}"%(q)
#post_data中主要修改的是:service_id(提前准备好的机器人id)、type(TEXT为常规的文本型,EVENT为一组K-V(json),且其中必须包含一个名为『event_name』的key,其他自便)、source("ASR","KEYBOARD"。ASR为语音输入,KEYBOARD为键盘文本输入。针对ASR输入,UNIT平台内置了纠错机制,会尝试解决语音输入中的一些常见错误)
#print('post_data:',post_data)
headers = {
    
    'content-type': 'application/x-www-form-urlencoded'}   #不用管
response = requests.post(url, data=post_data.encode('utf-8'), headers=headers)
#post_data.encode('utf-8'),需要先将post_data编码为‘utf-8’格式,否则会出错
if response:
    print (response.json())

At last

For the calls of other Baidu API series, please refer to https://blog.csdn.net/weixin_45386875/article/details/113705329

Guess you like

Origin blog.csdn.net/weixin_45386875/article/details/113743752