AI大模型教程
一起来学习

百度文心一言API调用全流程详解:从鉴权到实战(附代码示例)

引言

百度文心一言(ERNIE Bot)作为领先的自然语言处理大模型,其API调用能力被广泛应用于智能客服、内容生成、数据分析等场景。本文基于官方流程梳理**完整调用步骤**,结合实战代码和避坑指南,助你高效接入文心一言API!

一、调用流程总览

根据思维导图,调用流程分为三大阶段:  
1. **鉴权认证**:获取API调用权限。  
2. **参数处理**:规范请求格式。  
3. **调用与响应**:执行请求并解析结果。

 

文兴一言api调用流程图:  

二、分步详解与代码实战

1. 鉴权流程:获取API调用凭证
步骤说明:  

①获取AK/SK:从百度智能云控制台申请API Key(AK)和Secret Key(SK)。  
②生成Authorization:通过AK/SK生成签名,确保请求合法性。  

代码示例(Python):  

import requests
import hashlib
import hmac
import base64
from urllib.parse import urlencode

# 替换为你的AK/SK
AK = "your_access_key"
SK = "your_secret_key"



# 生成鉴权签名
def get_authorization():
    timestamp = str(int(time.time()))
    signature = hmac.new(SK.encode('utf-8'), timestamp.encode('utf-8'), hashlib.sha256).digest()
    signature = base64.b64encode(signature).decode('utf-8')
    return f'ak={AK}&timestamp={timestamp}&signature={signature}'

authorization = get_authorization()

 

2. 请求参数处理:JSON格式化与编码 
关键操作:  
①将输入文本、模型参数等封装为JSON。  
② 添加`access_token`(通过鉴权获取)。  

**示例请求体**:  

json
{
  "header": {
    "app_id": "your_app_id"
  },
  "payload": {
    "message": {
      "text": "你好,请生成一篇关于AI的短文。"
    }
  }
}

 

3. 发起API请求与结果解析
代码示例(Python):  

url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"

headers = {
    "Content-Type": "application/json",
    "Authorization": authorization
}

response = requests.post(url, headers=headers, json=payload)
result = response.json()

if result["error_code"] == 0:
    print("生成结果:", result["result"]["response"])
else:
    print("请求失败:", result["error_msg"])

 

4.完整调用代码(单句回复)

该代码段在可执行单句会回复

import requests
import json
class WenxinAI:
        def __init__(self):
                
                self.API_KEY = "N5jT65E9Pc4erGBvaWci9X0Vv" # 此处直接替换xxxxxxx为获取到的 API_KEY

                self.SECRET_KEY = "BcUT78xKyeMfvjGC1JxvRyfrz1slKmB" # 此处直接替换xxxxxxx为获取到的 SECRET_KEY
                self.ACCESS_TOKEN=self.get_access_token()
                
        def get_access_token(self):
                url="https://aip.baidubce.com/oauth/2.0/token"
                params={
                        "grant_type":"client_credentials",
                        "client_id":self.API_KEY,
                        "client_secret":self.SECRET_KEY
                        }
                return str(requests.post(url,params=params).json().get("access_token"))

        def chat(self,text):
                url=("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token="+self.ACCESS_TOKEN)
                payload=json.dumps({"messages":[{"role":"user","content":text}]})
                headers={"Content-Type":"application/json"}
                response=requests.request("post",url,headers=headers,data=payload)
                return response.json()["result"]

Twenxin_AI=WenxinAI()

chat_text="你是谁呀"#设置问题语句,可回复单句
result=Twenxin_AI.chat(chat_text)
print(result)

运行图


三、注意事项与最佳实践

  
1. 安全管控:  

   • AK/SK需存储在环境变量或加密配置中,**切勿暴露在代码仓库**。  
   • 建议定期轮换密钥。  

2. 错误处理:  
   • 检查HTTP状态码(如429限频、401鉴权失败)。  
   • 添加重试机制(如指数退避)。  

3. 性能优化:  
   • 使用连接池(如`requests.Session`)减少延迟。  
   • 异步调用提升吞吐量(如`aiohttp`库)。  

四、结语  

通过上述流程,你可以快速完成文心一言API的集成。实际开发中,建议结合官方文档[百度智能云-文心一言API](https://cloud.baidu.com/product/wenxinworkshop)调整参数细节。如有疑问,欢迎在评论区交流!

#### **附录**  
• [文心一言API官方文档](https://cloud.baidu.com/doc/WENXINWORKSHOP/s/8lkil9z8u)  

— 

**立即动手实践,解锁文心一言的强大能力吧!** 🚀

文章来源于互联网:百度文心一言API调用全流程详解:从鉴权到实战(附代码示例)

相关推荐: ubuntu-学习笔记-nginx+php

记录一下在ubuntu中nginx+php部署tp项目 nginx nginx就是正常下载 下载nginx sudo apt-get install nginx tp项目版本是3.2,通过设置路由,以域名/api.php/控制器/xxx的格式进行api的调用,…

赞(0)
未经允许不得转载:5bei.cn大模型教程网 » 百度文心一言API调用全流程详解:从鉴权到实战(附代码示例)
分享到: 更多 (0)

AI大模型,我们的未来

小欢软考联系我们