Python調用豆包API的完整指南
準備工作
在開始之前,您需要:
- 注冊豆包開發(fā)者賬號
- 獲取API密鑰(通常在開發(fā)者控制臺中創(chuàng)建應用后獲得)
- 安裝必要的Python庫
安裝所需庫
pip install requests # 用于HTTP請求 pip install python-dotenv # 用于管理環(huán)境變量(可選)
基本API調用
首先,讓我們實現(xiàn)一個簡單的豆包API調用:
import requests import json def call_doubao_api(api_key, prompt, model="doubao-pro"): """ 調用豆包API的基本函數 參數: api_key: 您的豆包API密鑰 prompt: 輸入的提示文本 model: 使用的模型版本,默認為'doubao-pro' 返回: API的響應內容 """ 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調用失敗,狀態(tài)碼: {response.status_code}, 錯誤: {response.text}") # 使用示例 api_key = "your_api_key_here" # 替換為您的實際API密鑰 response = call_doubao_api(api_key, "Python是什么?") print(response["choices"][0]["message"]["content"])
高級功能實現(xiàn)
1. 多輪對話
豆包API支持多輪對話,只需在messages數組中包含歷史消息:
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. 流式響應
對于長文本響應,可以使用流式接收:
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", "請詳細解釋Python的生成器")
錯誤處理與重試機制
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) # 指數退避 except Exception as e: last_error = e break raise Exception(f"API調用失敗,重試{max_retries}次后仍不成功。最后錯誤: {str(last_error)}")
實際應用示例
1. 代碼生成與解釋
def generate_code_explanation(api_key, code_snippet): prompt = f""" 請解釋以下Python代碼的功能和工作原理: {code_snippet} 請按照以下格式回答: 1. 代碼功能概述 2. 關鍵代碼段解析 3. 可能的改進建議 """ response = robust_doubao_call(api_key, prompt) return response["choices"][0]["message"]["content"]
2. 內容摘要生成
def generate_summary(api_key, text, length="short"): length_map = { "short": "50字以內", "medium": "100-150字", "long": "200-300字" } prompt = f""" 請為以下文本生成一個{length_map.get(length, "適中")}的摘要: {text} 摘要要求: - 保留核心信息 - 語言簡潔明了 - 保持客觀中立 """ response = robust_doubao_call(api_key, prompt) return response["choices"][0]["message"]["content"]
最佳實踐
API密鑰管理:不要將API密鑰硬編碼在代碼中,使用環(huán)境變量或密鑰管理服務
from dotenv import load_dotenv import os load_dotenv() api_key = os.getenv("DOUBAO_API_KEY")
速率限制:豆包API可能有速率限制,適當添加延遲或實現(xiàn)隊列機制
輸入驗證:對用戶輸入進行清理和驗證,防止注入攻擊
緩存響應:對于頻繁相同的請求,考慮實現(xiàn)緩存機制
監(jiān)控與日志:記錄API調用情況,便于調試和優(yōu)化
結語
通過Python調用豆包API,您可以輕松將強大的AI對話能力集成到您的應用中。本文介紹了從基礎調用到高級功能的實現(xiàn)方法,以及錯誤處理和最佳實踐。隨著豆包API的不斷更新,建議定期查閱官方文檔以獲取最新功能和參數。
以上就是Python調用豆包API的完整指南的詳細內容,更多關于Python調用豆包API的資料請關注腳本之家其它相關文章!
相關文章
django項目環(huán)境搭建及在虛擬機本地創(chuàng)建django項目的教程
這篇文章主要介紹了django項目環(huán)境搭建及在虛擬機本地創(chuàng)建django項目的教程,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08Python使用pandas導入xlsx格式的excel文件內容操作代碼
這篇文章主要介紹了Python使用pandas導入xlsx格式的excel文件內容,基本導入是在Python中使用pandas導入.xlsx文件的方法是read_excel(),本文結合示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-12-12