Python調(diào)用豆包API的完整指南
準(zhǔn)備工作
在開始之前,您需要:
- 注冊(cè)豆包開發(fā)者賬號(hào)
- 獲取API密鑰(通常在開發(fā)者控制臺(tái)中創(chuàng)建應(yīng)用后獲得)
- 安裝必要的Python庫(kù)
安裝所需庫(kù)
pip install requests # 用于HTTP請(qǐng)求 pip install python-dotenv # 用于管理環(huán)境變量(可選)
基本API調(diào)用
首先,讓我們實(shí)現(xiàn)一個(gè)簡(jiǎn)單的豆包API調(diào)用:
import requests
import json
def call_doubao_api(api_key, prompt, model="doubao-pro"):
"""
調(diào)用豆包API的基本函數(shù)
參數(shù):
api_key: 您的豆包API密鑰
prompt: 輸入的提示文本
model: 使用的模型版本,默認(rèn)為'doubao-pro'
返回:
API的響應(yīng)內(nèi)容
"""
url = "https://api.doubao.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"model": model,
"messages": [
{"role": "user", "content": prompt}
],
"temperature": 0.7
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"API調(diào)用失敗,狀態(tài)碼: {response.status_code}, 錯(cuò)誤: {response.text}")
# 使用示例
api_key = "your_api_key_here" # 替換為您的實(shí)際API密鑰
response = call_doubao_api(api_key, "Python是什么?")
print(response["choices"][0]["message"]["content"])
高級(jí)功能實(shí)現(xiàn)
1. 多輪對(duì)話
豆包API支持多輪對(duì)話,只需在messages數(shù)組中包含歷史消息:
def multi_turn_conversation(api_key):
conversation_history = []
while True:
user_input = input("你: ")
if user_input.lower() in ["退出", "exit", "quit"]:
break
conversation_history.append({"role": "user", "content": user_input})
response = call_doubao_api(
api_key=api_key,
prompt=conversation_history,
model="doubao-pro"
)
assistant_reply = response["choices"][0]["message"]["content"]
conversation_history.append({"role": "assistant", "content": assistant_reply})
print(f"豆包: {assistant_reply}")
# 使用示例
# multi_turn_conversation("your_api_key_here")
2. 流式響應(yīng)
對(duì)于長(zhǎng)文本響應(yīng),可以使用流式接收:
def stream_doubao_response(api_key, prompt):
url = "https://api.doubao.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"model": "doubao-pro",
"messages": [{"role": "user", "content": prompt}],
"stream": True
}
with requests.post(url, headers=headers, json=data, stream=True) as response:
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith("data:"):
json_data = decoded_line[5:].strip()
if json_data != "[DONE]":
try:
chunk = json.loads(json_data)
content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
print(content, end="", flush=True)
except json.JSONDecodeError:
pass
print()
# 使用示例
# stream_doubao_response("your_api_key_here", "請(qǐng)?jiān)敿?xì)解釋Python的生成器")
錯(cuò)誤處理與重試機(jī)制
import time
from requests.exceptions import RequestException
def robust_doubao_call(api_key, prompt, max_retries=3):
retries = 0
last_error = None
while retries < max_retries:
try:
response = call_doubao_api(api_key, prompt)
return response
except RequestException as e:
last_error = e
retries += 1
if retries < max_retries:
time.sleep(2 ** retries) # 指數(shù)退避
except Exception as e:
last_error = e
break
raise Exception(f"API調(diào)用失敗,重試{max_retries}次后仍不成功。最后錯(cuò)誤: {str(last_error)}")
實(shí)際應(yīng)用示例
1. 代碼生成與解釋
def generate_code_explanation(api_key, code_snippet):
prompt = f"""
請(qǐng)解釋以下Python代碼的功能和工作原理:
{code_snippet}
請(qǐng)按照以下格式回答:
1. 代碼功能概述
2. 關(guān)鍵代碼段解析
3. 可能的改進(jìn)建議
"""
response = robust_doubao_call(api_key, prompt)
return response["choices"][0]["message"]["content"]
2. 內(nèi)容摘要生成
def generate_summary(api_key, text, length="short"):
length_map = {
"short": "50字以內(nèi)",
"medium": "100-150字",
"long": "200-300字"
}
prompt = f"""
請(qǐng)為以下文本生成一個(gè){length_map.get(length, "適中")}的摘要:
{text}
摘要要求:
- 保留核心信息
- 語言簡(jiǎn)潔明了
- 保持客觀中立
"""
response = robust_doubao_call(api_key, prompt)
return response["choices"][0]["message"]["content"]
最佳實(shí)踐
API密鑰管理:不要將API密鑰硬編碼在代碼中,使用環(huán)境變量或密鑰管理服務(wù)
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("DOUBAO_API_KEY")
速率限制:豆包API可能有速率限制,適當(dāng)添加延遲或?qū)崿F(xiàn)隊(duì)列機(jī)制
輸入驗(yàn)證:對(duì)用戶輸入進(jìn)行清理和驗(yàn)證,防止注入攻擊
緩存響應(yīng):對(duì)于頻繁相同的請(qǐng)求,考慮實(shí)現(xiàn)緩存機(jī)制
監(jiān)控與日志:記錄API調(diào)用情況,便于調(diào)試和優(yōu)化
結(jié)語
通過Python調(diào)用豆包API,您可以輕松將強(qiáng)大的AI對(duì)話能力集成到您的應(yīng)用中。本文介紹了從基礎(chǔ)調(diào)用到高級(jí)功能的實(shí)現(xiàn)方法,以及錯(cuò)誤處理和最佳實(shí)踐。隨著豆包API的不斷更新,建議定期查閱官方文檔以獲取最新功能和參數(shù)。
以上就是Python調(diào)用豆包API的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Python調(diào)用豆包API的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
pandas 使用merge實(shí)現(xiàn)百倍加速的操作
這篇文章主要介紹了pandas 使用merge實(shí)現(xiàn)百倍加速的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04
感知器基礎(chǔ)原理及python實(shí)現(xiàn)過程詳解
這篇文章主要介紹了感知器基礎(chǔ)原理及python實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
Python3中簡(jiǎn)單的文件操作及兩個(gè)簡(jiǎn)單小實(shí)例分享
文件操作是我們?nèi)粘T谑褂胮ython的時(shí)候經(jīng)常會(huì)用到的,下面這篇文章主要給大家介紹了關(guān)于Python3中簡(jiǎn)單的文件操作及兩個(gè)簡(jiǎn)單小實(shí)例的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。2017-06-06
django項(xiàng)目環(huán)境搭建及在虛擬機(jī)本地創(chuàng)建django項(xiàng)目的教程
這篇文章主要介紹了django項(xiàng)目環(huán)境搭建及在虛擬機(jī)本地創(chuàng)建django項(xiàng)目的教程,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08
Python使用pandas導(dǎo)入xlsx格式的excel文件內(nèi)容操作代碼
這篇文章主要介紹了Python使用pandas導(dǎo)入xlsx格式的excel文件內(nèi)容,基本導(dǎo)入是在Python中使用pandas導(dǎo)入.xlsx文件的方法是read_excel(),本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12
python實(shí)現(xiàn)Web請(qǐng)求與響應(yīng)超詳細(xì)指南
Web請(qǐng)求是客戶端向服務(wù)器發(fā)起的資源獲取或操作請(qǐng)求,這篇文章主要介紹了python實(shí)現(xiàn)Web請(qǐng)求與響應(yīng)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-05-05

