百度UNIT API3.0调用代码

百度智能对话定制与服务平台(UNIT)机器人对话API。
基于 https://github.com/fredfeng0326/baidu_talk 改进
更多内容参见官方文档 https://ai.baidu.com/ai-doc/UNIT/qkpzeloou

import urllib.request as urllib2
import json

class baidu_unit():
    token = ''

    # service_id: 机器人id
    # session_id: 实现多轮对话                  
    # log_id: AppID? 技能ID?
    post_data_prefix = "{\"version\":\"3.0\",\"service_id\":\"S69358\",\"session_id\":\"\",\"log_id\":\"26227257\",\"request\":{\"terminal_id\":\"88888\",\"query\":\""

    def fetch_token(self):
        API_Key = ''
        Secret_Key = ''

        host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_Key}&client_secret={Secret_Key}'
        request = urllib2.Request(host)
        request.add_header('Content-Type', 'application/json; charset=UTF-8')
        content = urllib2.urlopen(request).read()
        my_json = content.decode('utf8').replace("'", '"')
        data = json.loads(my_json)
        if data:
            self.token = data['access_token']
        else:
            print("[ERROR]: 调用unit时获取token失败")

    def get_unit_reply(self, user_text):
        url = 'https://aip.baidubce.com/rpc/2.0/unit/service/v3/chat?access_token=' + self.token

        post_data = self.post_data_prefix + user_text + "\"}}"

        request = urllib2.Request(url, bytearray(post_data, 'utf8'))
        request.add_header('Content-Type', 'application/json')
        response = urllib2.urlopen(request)

        content_json = json.loads(response.read().decode('utf8'))  # 转为dict

        # 处理session_id:第一次请求是,session_id 值为空,以后应该填上返回的值,如此才能实现多轮会话
        if self.post_data_prefix[53] == '"':
            self.post_data_prefix = self.post_data_prefix[:53] + content_json['result']['session_id'] + self.post_data_prefix[53:]

        reply = content_json['result']['responses'][0]['actions'][0]['say']  # 提取回答
        print(f"[Bot]: {reply}")

        return reply
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dreamingcoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值