百度 unit API

百度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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容