美文网首页
百度 unit API

百度 unit API

作者: Jlan | 来源:发表于2019-08-09 18:02 被阅读0次

    百度unit API

    1. 获取access_token

    参考http://ai.baidu.com/docs#/Auth/top

    import requests
    import ssl
    
    def get_access_token(api_key, secret_key):
        # client_id 为官网获取的AK, client_secret 为官网获取的SK
        url = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={api_key}&client_secret={secret_key}'
        headers = {'Content-Type': 'application/json; charset=UTF-8'}
        response = requests.post(url, headers=headers)
        return response.json()['access_token']
    
    api_key = '
    secret_key = ''
    access_token = get_access_token(api_key, secret_key)
    

    2. unit api

    参考https://ai.baidu.com/docs#/UNIT-v2-service-API/c3cd4b5e

    import json
    import requests
    
    
    def chat_baidu(access_token, text='你好'):
        headers = {'Content-Type':'application/json'}
        access_token = access_token
        url = f'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": "S21125", 
        #     "skill_ids": ['73803', '73808', '73809', '73810', '73811'],
            "session_id": '', 
            "request": {"query": text, "user_id": "88888"}, 
        #     "dialog_state":{"contexts": {"SYS_REMEMBERED_SKILLS":["1057"]}}
        }
        
        try:
            response = requests.post(url, data=json.dumps(post_data), headers=headers)
            if not response.ok:
                raise Exception
            response = response.json()
            if response['error_code']:
                raise Exception(response['error_msg'])
            results = response['result']['response_list'][0]['action_list'][0]['say']
            print(results)
        except Exception as e:
            print(f'error: {e}')
        else:
            return results
    

    相关文章

      网友评论

          本文标题:百度 unit API

          本文链接:https://www.haomeiwen.com/subject/pbayjqtx.html