前言
首先我选择的siliconflow(硅基流动)平台来调用它的api
不为啥,就是因为我点击了别人的邀请链接它送了我14块余额,那个人同样也获得14块余额
这时候,就不得不说一下我的邀请链接了https://cloud.siliconflow.cn/i/ON1CM4GS
之所以使用python调用API,多是想要实现自动化的操作
步骤:
1.首先注册后,在API 密钥处创建一个密钥

2.在模型广场处,选择要使用模型,点开,我这里选择的是Pro/deepseek-ai/DeepSeek-R1
3.点击API文档后,我们根据需要不同以及代码类型进行选择
4.替换为相关信息,如Bearer 后接第一步的API密钥,以及payload = {"model": "Pro/deepseek-ai/DeepSeek-V3"}
处的模型选择
5.代码展示
配置API参数
# 配置API参数
API_KEY = "sk-pfkwspsjowmfxjgncpdtmwzujoiuisscssgjsncqmpdhmwfn"
BASE_URL = "https://api.siliconflow.cn/v1/chat/completions"
HEADERS = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
调用API生成文本
def call_deepseek_api(prompt):
max_retries = 5 # 最大重试次数
retry_delay = 1 # 重试间隔时间(秒)
for attempt in range(max_retries):
data = {
"model": "deepseek-ai/DeepSeek-V3",
"messages": [
{"role": "user", "content": prompt}
],
"max_tokens": 1024,
"temperature": 0.7
}
response = requests.post(BASE_URL, headers=HEADERS, json=data)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
elif response.status_code == 504 and attempt < max_retries - 1:
print(f"请求超时(504),正在第 {attempt + 1} 次重试...")
time.sleep(retry_delay)
else:
return f"Error: {response.status_code} - {response.text}"
return "Error: 达到最大重试次数,请求失败。"
如果有用的话,不妨用一下我的邀请链接https://cloud.siliconflow.cn/i/ON1CM4GS,让我们互加余额