百度文心大模型python调用例程🌞

API KEY申请

先去下方网址申请apikey:

百度智能云千帆大模型 (baidu.com)

python对接


# 填充API Key与Secret Key
import requests
import json

API_KEY = ""
SECRET_KEY = ""

def get_access_token():
    """
    使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    """
        
    url = "https://aip.baidubce.com/oauth/2.0/token?client_id="+API_KEY+"&client_secret="+SECRET_KEY+"&grant_type=client_credentials"
    
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main():
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token()
    
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": input("请输入您的问题:")
            }
            
        ],
         "stream": False
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    res = json.loads(response.text)
    print(res['result']) 
    #for line in response.iter_lines():
        #print(line.decode('utf-8'))

if __name__ == '__main__':
    main()

效果展示