简介:ERNIE 4.5是百度自研的旗舰级超大规模⼤语⾔模型,相较ERNIE 4.0实现了模型能力全面升级,广泛适用于各领域复杂任务场景。以下是适合新手的文心大模型4.5 API调用全流程指南
应用创建后,选择对应授权的公有云服务。
import requests
import time
class TokenManager:
def __init__(self, api_key, secret_key):
self.api_key = api_key
self.secret_key = secret_key
self.token = None
self.expire_time = 0
def get_token(self):
if time.time() < self.expire_time - 300: # 提前5分钟刷新
return self.token
url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={self.api_key}&client_secret={self.secret_key}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
self.token = data['access_token']
self.expire_time = time.time() + data['expires_in']
return self.token
else:
raise Exception(f"获取token失败: {response.text}")
# 使用示例
token_mgr = TokenManager("您的API Key", "您的Secret Key")
access_token = token_mgr.get_token()
使用AppID、Access Token和模型接口URL调用文心一言,详见API列表。
\百度智能云千帆提供了** API在线调试平台-示例代码 \,用于帮助开发者调试接口**,平台集成快速检索、查看开发文档、查看在线调用的请求内容和返回结果、复制和下载示例代码等功能,简单易用,更多内容请查看API在线调试介绍。
# Windows用户推荐使用Anaconda
conda create -n wenxin python=3.9
conda activate wenxin
# 安装官方SDK(含4.5支持)
pip install qianfan
\方法一:环境变量配置(推荐)**
# Windows系统
setx QIANFAN_AK "your-api-key"
setx QIANFAN_SK "your-secret-key"
# Mac/Linux
export QIANFAN_AK="your-api-key"
export QIANFAN_SK="your-secret-key"
\方法二:代码内显式声明**
import qianfan
qianfan.AK("your-api-key")
qianfan.SK("your-secret-key")
# 导入库
from qianfan.resources import ChatCompletion
def simple_chat(question):
# 初始化对话客户端
chat = ChatCompletion(model="ERNIE-Bot-4.5")
# 构建对话结构
messages = [{
"role": "user",
"content": question
}]
# 发起API请求
resp = chat.do(
messages=messages,
temperature=0.8, # 控制创造性(0-1,越大结果越多样)
top_p=0.9, # 采样范围(0-1,越小结果越确定)
max_output_tokens=500 # 限制响应长度
)
# 处理响应结果
if resp.code == 200:
print("【AI回答】", resp.body["result"])
print("本次消耗token数:", resp.body["usage"])
else:
print("请求失败,错误码:", resp.code)
# 测试对话
if __name__ == "__main__":
user_input = input("请输入您的问题:")
simple_chat(user_input)
错误现象 | 解决方案 |
---|---|
ModuleNotFoundError: No module named 'qianfan' |
执行 pip install qianfan --upgrade |
Error code: 110 |
检查AK/SK是否正确且未过期 |
响应内容不全 | 增大 max_output_tokens 参数值 |
长时间无响应 | 添加 request_timeout=30 参数限制超时 |
max_output_tokens=1000
temperature=0.3
(降低随机性)system
角色提示词:
messages = [
{"role": "system", "content": "你是一名资深IT架构师"},
{"role": "user", "content": "如何设计高并发系统?"}
]
stream=True
参数实现逐字输出效果knowledge_id
参数通过以上步骤,即使没有AI开发经验的用户,也可以在30分钟内完成首次API调用。建议从简单问答开始(如天气咨询、百科查询),逐步尝试复杂场景(多轮对话、表格生成等)。