文章目录
- 豆包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”)
- 对于长文本响应,可以使用流式接收: 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的生成器”)
- 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”]
- 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调用
- 高级功能实现
- 1. 多轮对话
- 2. 流式响应
- 错误处理与重试机制
- 实际应用示例
- 1. 代码生成与解释
- 2. 内容摘要生成
- 最佳实践
- 结语
在开始之前,您需要:
- 注册豆包开发者账号
- 获取API密钥(通常在开发者控制台中创建应用后获得)
- 安装必要的Python库
pip install requests # 用于HTTP请求
pip install python-dotenv # 用于管理环境变量(可选)
首先,让我们实现一个简单的豆包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调用失败,状态码: {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"])
豆包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")
对于长文本响应,可以使用流式接收:
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)}")
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"]
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密钥硬编码在代码中,使用环境变量或密钥管理服务
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("DOUBAO_API_KEY")
速率限制:豆包API可能有速率限制,适当添加延迟或实现队列机制
输入验证:对用户输入进行清理和验证,防止注入攻击
缓存响应:对于频繁相同的请求,考虑实现缓存机制
监控与日志:记录API调用情况,便于调试和优化
通过Python调用豆包API,您可以轻松将强大的AI对话能力集成到您的应用中。本文介绍了从基础调用到高级功能的实现方法,以及错误处理和最佳实践。随着豆包API的不断更新,建议定期查阅官方文档以获取最新功能和参数。
以上就是Python调用豆包API的完整指南的详细内容,更多关于Python调用豆包API的资料请关注风君子博客其它相关文章!
您可能感兴趣的文章:
- 以文档处理为例讲解豆包API调用教程(Python)
- Python调用API的常用方式解析
- Python调用AnythingLLM API使用流输出的实现
- python使用django调用deepseek api搭建ai网站
- Python调用DeepSeek API的案例详细教程